svncommit
2005-10-27 c9462d0c1e2493a7399b1dbd21e23b215e97f808
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, Frank M. Kromann                       |
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 /**
50  * MDB2 FrontBase driver
51  *
52  * @package MDB2
53  * @category Database
54  * @author  Lukas Smith <smith@pooteeweet.org>
55  * @author  Frank M. Kromann <frank@kromann.info>
56  */
57 class MDB2_Driver_fbsql extends MDB2_Driver_Common
58 {
59     // {{{ properties
60     var $escape_quotes = "'";
61
62     // }}}
63     // {{{ constructor
64
65     /**
66     * Constructor
67     */
68     function __construct()
69     {
70         parent::__construct();
71
72         $this->phptype = 'fbsql';
73         $this->dbsyntax = 'fbsql';
74
75         $this->supported['sequences'] = 'emulated';
76         $this->supported['indexes'] = true;
77         $this->supported['affected_rows'] = true;
78         $this->supported['transactions'] = true;
79         $this->supported['summary_functions'] = true;
80         $this->supported['order_by_text'] = true;
81         $this->supported['current_id'] = 'emulated';
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
90     // }}}
91     // {{{ errorInfo()
92
93     /**
94      * This method is used to collect information about an error
95      *
96      * @param integer $error
97      * @return array
98      * @access public
99      */
100     function errorInfo($error = null)
101     {
102        if ($this->connection) {
103            $native_code = @fbsql_errno($this->connection);
104            $native_msg  = @fbsql_error($this->connection);
105        } else {
106            $native_code = @fbsql_errno();
107            $native_msg  = @fbsql_error();
108        }
109         if (is_null($error)) {
110             static $ecode_map;
111             if (empty($ecode_map)) {
112                 $ecode_map = array(
113                      22 => MDB2_ERROR_SYNTAX,
114                      85 => MDB2_ERROR_ALREADY_EXISTS,
115                     108 => MDB2_ERROR_SYNTAX,
116                     116 => MDB2_ERROR_NOSUCHTABLE,
117                     124 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
118                     215 => MDB2_ERROR_NOSUCHFIELD,
119                     217 => MDB2_ERROR_INVALID_NUMBER,
120                     226 => MDB2_ERROR_NOSUCHFIELD,
121                     231 => MDB2_ERROR_INVALID,
122                     239 => MDB2_ERROR_TRUNCATED,
123                     251 => MDB2_ERROR_SYNTAX,
124                     266 => MDB2_ERROR_NOT_FOUND,
125                     357 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
126                     358 => MDB2_ERROR_CONSTRAINT,
127                     360 => MDB2_ERROR_CONSTRAINT,
128                     361 => MDB2_ERROR_CONSTRAINT,
129                 );
130             }
131             if (isset($ecode_map[$native_code])) {
132                 $error = $ecode_map[$native_code];
133             }
134         }
135         return array($error, $native_code, $native_msg);
136     }
137
138     // }}}
139     // {{{ beginTransaction()
140
141     /**
142      * Start a transaction.
143      *
144      * @return mixed MDB2_OK on success, a MDB2 error on failure
145      * @access public
146      */
147     function beginTransaction()
148     {
149         $this->debug('starting transaction', 'beginTransaction');
150         if ($this->in_transaction) {
151             return MDB2_OK;  //nothing to do
152         }
153         if (!$this->destructor_registered && $this->opened_persistent) {
154             $this->destructor_registered = true;
155             register_shutdown_function('MDB2_closeOpenTransactions');
156         }
157         $result = $this->_doQuery('SET COMMIT FALSE;', true);
158         if (PEAR::isError($result)) {
159             return $result;
160         }
161         $this->in_transaction = true;
162         return MDB2_OK;
163     }
164
165     // }}}
166     // {{{ commit()
167
168     /**
169      * Commit the database changes done during a transaction that is in
170      * progress.
171      *
172      * @return mixed MDB2_OK on success, a MDB2 error on failure
173      * @access public
174      */
175     function commit()
176     {
177         $this->debug('commit transaction', 'commit');
178         if (!$this->in_transaction) {
179             return $this->raiseError(MDB2_ERROR, null, null,
180                 'commit: transaction changes are being auto commited');
181         }
182         $result = $this->_doQuery('COMMIT;', true);
183         if (PEAR::isError($result)) {
184             return $result;
185         }
186         $result = $this->_doQuery('SET COMMIT TRUE;', true);
187         if (PEAR::isError($result)) {
188             return $result;
189         }
190         $this->in_transaction = false;
191         return MDB2_OK;
192     }
193
194     // }}}
195     // {{{ rollback()
196
197     /**
198      * Cancel any database changes done during a transaction that is in
199      * progress.
200      *
201      * @return mixed MDB2_OK on success, a MDB2 error on failure
202      * @access public
203      */
204     function rollback()
205     {
206         $this->debug('rolling back transaction', 'rollback');
207         if (!$this->in_transaction) {
208             return $this->raiseError(MDB2_ERROR, null, null,
209                 'rollback: transactions can not be rolled back when changes are auto committed');
210         }
211         $result = $this->_doQuery('ROLLBACK;', true);
212         if (PEAR::isError($result)) {
213             return $result;
214         }
215         $result = $this->_doQuery('SET COMMIT TRUE;', true);
216         if (PEAR::isError($result)) {
217             return $result;
218         }
219         $this->in_transaction = false;
220         return MDB2_OK;
221     }
222
223     // }}}
224     // {{{ connect()
225
226     /**
227      * Connect to the database
228      *
229      * @return true on success, MDB2 Error Object on failure
230      **/
231     function connect()
232     {
233         if (is_resource($this->connection)) {
234             if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
235                 && $this->opened_persistent == $this->options['persistent']
236             ) {
237                 return MDB2_OK;
238             }
239             $this->disconnect(false);
240         }
241
242         if (!PEAR::loadExtension($this->phptype)) {
243             return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
244                 'connect: extension '.$this->phptype.' is not compiled into PHP');
245         }
246
247         $params = array(
248             $this->dsn['hostspec'] ? $this->dsn['hostspec'] : 'localhost',
249             $this->dsn['username'] ? $this->dsn['username'] : null,
250             $this->dsn['password'] ? $this->dsn['password'] : null,
251         );
252
253         $connect_function = $this->options['persistent'] ? 'fbsql_pconnect' : 'fbsql_connect';
254
255         @ini_set('track_errors', true);
256         $php_errormsg = '';
257         $connection = @call_user_func_array($connect_function, $params);
258         @ini_restore('track_errors');
259         if ($connection <= 0) {
260             return $this->raiseError(MDB2_ERROR_CONNECT_FAILED);
261         }
262
263         $this->connection = $connection;
264         $this->connected_dsn = $this->dsn;
265         $this->connected_database_name = '';
266         $this->opened_persistent = $this->options['persistent'];
267         $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
268
269         return MDB2_OK;
270     }
271
272     // }}}
273     // {{{ disconnect()
274
275     /**
276      * Log out and disconnect from the database.
277      *
278      * @return mixed true on success, false if not connected and error
279      *                object on error
280      * @access public
281      */
282     function disconnect($force = true)
283     {
284         if (is_resource($this->connection)) {
285             if (!$this->opened_persistent || $force) {
286                 @fbsql_close($this->connection);
287             }
288             $this->connection = 0;
289         }
290         return MDB2_OK;
291     }
292
293     // }}}
294     // {{{ _doQuery()
295
296     /**
297      * Execute a query
298      * @param string $query  query
299      * @param boolean $isManip  if the query is a manipulation query
300      * @param resource $connection
301      * @param string $database_name
302      * @return result or error object
303      * @access protected
304      */
305     function _doQuery($query, $isManip = false, $connection = null, $database_name = null)
306     {
307         $this->last_query = $query;
308         $this->debug($query, 'query');
309         if ($this->options['disable_query']) {
310             if ($isManip) {
311                 return 0;
312             }
313             return null;
314         }
315
316         if (is_null($connection)) {
317             $err = $this->connect();
318             if (PEAR::isError($err)) {
319                 return $err;
320             }
321             $connection = $this->connection;
322         }
323         if (is_null($database_name)) {
324             $database_name = $this->database_name;
325         }
326
327         if ($database_name) {
328             if ($database_name != $this->connected_database_name) {
329                 if (!@fbsql_select_db($database_name, $connection)) {
330                     return $this->raiseError();
331                 }
332                 $this->connected_database_name = $database_name;
333             }
334         }
335
336         $result = @fbsql_query($query, $connection);
337         if (!$result) {
338             return $this->raiseError();
339         }
340
341         if ($isManip) {
342             return @fbsql_affected_rows($connection);
343         }
344         return $result;
345     }
346
347     // }}}
348     // {{{ _modifyQuery()
349
350     /**
351      * Changes a query string for various DBMS specific reasons
352      *
353      * @param string $query  query to modify
354      * @return the new (modified) query
355      * @access protected
356      */
357     function _modifyQuery($query, $isManip, $limit, $offset)
358     {
359         if ($limit > 0) {
360             if ($isManip) {
361                 return preg_replace('/^([\s(])*SELECT(?!\s*TOP\s*\()/i',
362                     "\\1SELECT TOP($limit)", $query);
363             } else {
364                 return preg_replace('/([\s(])*SELECT(?!\s*TOP\s*\()/i',
365                     "\\1SELECT TOP($offset,$limit)", $query);
366             }
367         }
368         // Add ; to the end of the query. This is required by FrontBase
369         return $query.';';
370     }
371
372     // }}}
373     // {{{ nextID()
374
375     /**
376      * returns the next free id of a sequence
377      *
378      * @param string $seq_name name of the sequence
379      * @param boolean $ondemand when true the seqence is
380      *                          automatic created, if it
381      *                          not exists
382      *
383      * @return mixed MDB2 Error Object or id
384      * @access public
385      */
386     function nextID($seq_name, $ondemand = true)
387     {
388         $sequence_name = $this->getSequenceName($seq_name);
389         $query = "INSERT INTO $sequence_name (".$this->options['seqcol_name'].") VALUES (NULL);";
390         $this->expectError(MDB2_ERROR_NOSUCHTABLE);
391         $result = $this->_doQuery($query, true);
392         $this->popExpect();
393         if (PEAR::isError($result)) {
394             if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
395                 $this->loadModule('Manager');
396                 // Since we are creating the sequence on demand
397                 // we know the first id = 1 so initialize the
398                 // sequence at 2
399                 $result = $this->manager->createSequence($seq_name, 2);
400                 if (PEAR::isError($result)) {
401                     return $this->raiseError(MDB2_ERROR, null, null,
402                         'nextID: on demand sequence '.$seq_name.' could not be created');
403                 } else {
404                     // First ID of a newly created sequence is 1
405                     return 1;
406                 }
407             }
408             return $result;
409         }
410         $value = $this->queryOne("SELECT UNIQUE FROM $sequence_name", 'integer');
411         if (is_numeric($value)) {
412             $query = "DELETE FROM $sequence_name WHERE ".$this->options['seqcol_name']." < $value;";
413             $result = $this->_doQuery($query, true);
414             if (PEAR::isError($result)) {
415                 $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
416             }
417         }
418         return $value;
419     }
420
421     // }}}
422     // {{{ lastInsertID()
423
424     /**
425      * returns the autoincrement ID if supported or $id
426      *
427      * @param mixed $id value as returned by getBeforeId()
428      * @param string $table name of the table into which a new row was inserted
429      * @return mixed MDB2 Error Object or id
430      * @access public
431      */
432     function lastInsertID($table = null, $field = null)
433     {
434         $value = @fbsql_insert_id($this->connection);
435         if (!$value) {
436             return $this->raiseError();
437         }
438         return $value;
439     }
440
441     // }}}
442     // {{{ currID()
443
444     /**
445      * returns the current id of a sequence
446      *
447      * @param string $seq_name name of the sequence
448      * @return mixed MDB2 Error Object or id
449      * @access public
450      */
451     function currID($seq_name)
452     {
453         $sequence_name = $this->getSequenceName($seq_name);
454         $query = "SELECT MAX(".$this->options['seqcol_name'].") FROM $sequence_name";
455         return $this->queryOne($query, 'integer');
456     }
457 }
458
459 class MDB2_Result_fbsql extends MDB2_Result_Common
460 {
461     // }}}
462     // {{{ fetchRow()
463
464     /**
465      * Fetch a row and insert the data into an existing array.
466      *
467      * @param int       $fetchmode  how the array data should be indexed
468      * @param int    $rownum    number of the row where the data can be found
469      * @return int data array on success, a MDB2 error on failure
470      * @access public
471      */
472     function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
473     {
474         if (!is_null($rownum)) {
475             $seek = $this->seek($rownum);
476             if (PEAR::isError($seek)) {
477                 return $seek;
478             }
479         }
480         if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
481             $fetchmode = $this->db->fetchmode;
482         }
483         if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
484             $row = @fbsql_fetch_assoc($this->result);
485             if (is_array($row)
486                 && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
487             ) {
488                 $row = array_change_key_case($row, $this->db->options['field_case']);
489             }
490         } else {
491            $row = @fbsql_fetch_row($this->result);
492         }
493         if (!$row) {
494             if (is_null($this->result)) {
495                 $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
496                     'fetchRow: resultset has already been freed');
497                 return $err;
498             }
499             $null = null;
500             return $null;
501         }
502         if ($this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL) {
503             $this->db->_fixResultArrayValues($row, MDB2_PORTABILITY_EMPTY_TO_NULL);
504         }
505         if (!empty($this->values)) {
506             $this->_assignBindColumns($row);
507         }
508         if (!empty($this->types)) {
509             $row = $this->db->datatype->convertResultRow($this->types, $row);
510         }
511         if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
512             $object_class = $this->db->options['fetch_class'];
513             if ($object_class == 'stdClass') {
514                 $row = (object) $row;
515             } else {
516                 $row = &new $object_class($row);
517             }
518         }
519         ++$this->rownum;
520         return $row;
521     }
522
523     // }}}
524     // {{{ _getColumnNames()
525
526     /**
527      * Retrieve the names of columns returned by the DBMS in a query result.
528      *
529      * @return mixed                an associative array variable
530      *                              that will hold the names of columns. The
531      *                              indexes of the array are the column names
532      *                              mapped to lower case and the values are the
533      *                              respective numbers of the columns starting
534      *                              from 0. Some DBMS may not return any
535      *                              columns when the result set does not
536      *                              contain any rows.
537      *
538      *                              a MDB2 error on failure
539      * @access private
540      */
541     function _getColumnNames()
542     {
543         $columns = array();
544         $numcols = $this->numCols();
545         if (PEAR::isError($numcols)) {
546             return $numcols;
547         }
548         for ($column = 0; $column < $numcols; $column++) {
549             $column_name = @fbsql_field_name($this->result, $column);
550             $columns[$column_name] = $column;
551         }
552         if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
553             $columns = array_change_key_case($columns, $this->db->options['field_case']);
554         }
555         return $columns;
556     }
557
558     // }}}
559     // {{{ numCols()
560
561     /**
562      * Count the number of columns returned by the DBMS in a query result.
563      *
564      * @return mixed integer value with the number of columns, a MDB2 error
565      *                       on failure
566      * @access public
567      */
568     function numCols()
569     {
570         $cols = @fbsql_num_fields($this->result);
571         if (is_null($cols)) {
572             if (is_null($this->result)) {
573                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
574                     'numCols: resultset has already been freed');
575             }
576             return $this->db->raiseError();
577         }
578         return $cols;
579     }
580
581     // }}}
582     // {{{ nextResult()
583
584     /**
585      * Move the internal result pointer to the next available result
586      * Currently not supported
587      *
588      * @return true if a result is available otherwise return false
589      * @access public
590      */
591     function nextResult()
592     {
593         if (is_null($this->result)) {
594             return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
595                 'nextResult: resultset has already been freed');
596         }
597         return @fbsql_next_result($this->result);
598     }
599
600     // }}}
601     // {{{ free()
602
603     /**
604      * Free the internal resources associated with result.
605      *
606      * @return boolean true on success, false if result is invalid
607      * @access public
608      */
609     function free()
610     {
611         $free = @fbsql_free_result($this->result);
612         if (!$free) {
613             if (is_null($this->result)) {
614                 return MDB2_OK;
615             }
616             return $this->db->raiseError();
617         }
618         $this->result = null;
619         return MDB2_OK;
620     }
621 }
622
623 class MDB2_BufferedResult_fbsql extends MDB2_Result_fbsql
624 {
625     // }}}
626     // {{{ seek()
627
628     /**
629     * seek to a specific row in a result set
630     *
631     * @param int    $rownum    number of the row where the data can be found
632     * @return mixed MDB2_OK on success, a MDB2 error on failure
633     * @access public
634     */
635     function seek($rownum = 0)
636     {
637         if ($this->rownum != ($rownum - 1) && !@fbsql_data_seek($this->result, $rownum)) {
638             if (is_null($this->result)) {
639                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
640                     'seek: resultset has already been freed');
641             }
642             return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
643                 'seek: tried to seek to an invalid row number ('.$rownum.')');
644         }
645         $this->rownum = $rownum - 1;
646         return MDB2_OK;
647     }
648
649     // }}}
650     // {{{ valid()
651
652     /**
653     * check if the end of the result set has been reached
654     *
655     * @return mixed true or false on sucess, a MDB2 error on failure
656     * @access public
657     */
658     function valid()
659     {
660         $numrows = $this->numRows();
661         if (PEAR::isError($numrows)) {
662             return $numrows;
663         }
664         return $this->rownum < ($numrows - 1);
665     }
666
667     // }}}
668     // {{{ numRows()
669
670     /**
671     * returns the number of rows in a result object
672     *
673     * @return mixed MDB2 Error Object or the number of rows
674     * @access public
675     */
676     function numRows()
677     {
678         $rows = @fbsql_num_rows($this->result);
679         if (is_null($rows)) {
680             if (is_null($this->result)) {
681                 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
682                     'numRows: resultset has already been freed');
683             }
684             return $this->raiseError();
685         }
686         return $rows;
687     }
688 }
689
690 class MDB2_Statement_fbsql extends MDB2_Statement_Common
691 {
692
693 }
694
695 ?>