]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/DB/fbsql.php
Remove svn:keywords
[SourceForge/phpwiki.git] / lib / pear / DB / fbsql.php
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
4 // | PHP Version 4                                                        |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2004 The PHP Group                                |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.02 of the PHP license,      |
9 // | that is bundled with this package in the file LICENSE, and is        |
10 // | available at through the world-wide-web at                           |
11 // | http://www.php.net/license/2_02.txt.                                 |
12 // | If you did not receive a copy of the PHP license and are unable to   |
13 // | obtain it through the world-wide-web, please send a note to          |
14 // | license@php.net so we can mail you a copy immediately.               |
15 // +----------------------------------------------------------------------+
16 // | Author: Frank M. Kromann <frank@frontbase.com>                       |
17 // | Maintainer: Daniel Convissor <danielc@php.net>                       |
18 // +----------------------------------------------------------------------+
19
20 // XXX legend:
21 //
22 // XXX ERRORMSG: The error message from the fbsql function should
23 //               be registered here.
24 //
25 // TODO/wishlist:
26 // longReadlen
27 // binmode
28
29 require_once 'DB/common.php';
30
31 /**
32  * Database independent query interface definition for PHP's FrontBase
33  * extension.
34  *
35  * @package  DB
36  * @version  
37  * @category Database
38  * @author   Frank M. Kromann <frank@frontbase.com>
39  */
40 class DB_fbsql extends DB_common
41 {
42     // {{{ properties
43
44     var $connection;
45     var $phptype, $dbsyntax;
46     var $prepare_tokens = array();
47     var $prepare_types = array();
48     var $num_rows = array();
49     var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
50
51     // }}}
52     // {{{ constructor
53
54     /**
55      * DB_fbsql constructor.
56      *
57      * @access public
58      */
59     function DB_fbsql()
60     {
61         $this->DB_common();
62         $this->phptype = 'fbsql';
63         $this->dbsyntax = 'fbsql';
64         $this->features = array(
65             'prepare' => false,
66             'pconnect' => true,
67             'transactions' => true,
68             'limit' => 'emulate'
69         );
70         $this->errorcode_map = array(
71             1004 => DB_ERROR_CANNOT_CREATE,
72             1005 => DB_ERROR_CANNOT_CREATE,
73             1006 => DB_ERROR_CANNOT_CREATE,
74             1007 => DB_ERROR_ALREADY_EXISTS,
75             1008 => DB_ERROR_CANNOT_DROP,
76             1046 => DB_ERROR_NODBSELECTED,
77             1050 => DB_ERROR_ALREADY_EXISTS,
78             1051 => DB_ERROR_NOSUCHTABLE,
79             1054 => DB_ERROR_NOSUCHFIELD,
80             1062 => DB_ERROR_ALREADY_EXISTS,
81             1064 => DB_ERROR_SYNTAX,
82             1100 => DB_ERROR_NOT_LOCKED,
83             1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
84             1146 => DB_ERROR_NOSUCHTABLE,
85         );
86     }
87
88     // }}}
89     // {{{ connect()
90
91     /**
92      * Connect to a database and log in as the specified user.
93      *
94      * @param $dsn the data source name (see DB::parseDSN for syntax)
95      * @param $persistent (optional) whether the connection should
96      *        be persistent
97      * @access public
98      * @return int DB_OK on success, a DB error on failure
99      */
100     function connect($dsninfo, $persistent = false)
101     {
102         if (!DB::assertExtension('fbsql')) {
103             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
104         }
105
106         $this->dsn = $dsninfo;
107         $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
108
109         $php_errormsg = '';
110         $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
111
112         if ($dbhost && $dsninfo['username'] && $dsninfo['password']) {
113             $conn = @$connect_function($dbhost, $dsninfo['username'],
114                                        $dsninfo['password']);
115         } elseif ($dbhost && $dsninfo['username']) {
116             $conn = @$connect_function($dbhost, $dsninfo['username']);
117         } elseif ($dbhost) {
118             $conn = @$connect_function($dbhost);
119         } else {
120             $conn = false;
121         }
122         if (!$conn) {
123             if (empty($php_errormsg)) {
124                 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
125             } else {
126                 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
127                                          null, $php_errormsg);
128             }
129         }
130
131         if ($dsninfo['database']) {
132             if (!fbsql_select_db($dsninfo['database'], $conn)) {
133                 return $this->fbsqlRaiseError();
134             }
135         }
136
137         $this->connection = $conn;
138         return DB_OK;
139     }
140
141     // }}}
142     // {{{ disconnect()
143
144     /**
145      * Log out and disconnect from the database.
146      *
147      * @access public
148      *
149      * @return bool true on success, false if not connected.
150      */
151     function disconnect()
152     {
153         $ret = @fbsql_close($this->connection);
154         $this->connection = null;
155         return $ret;
156     }
157
158     // }}}
159     // {{{ simpleQuery()
160
161     /**
162      * Send a query to fbsql and return the results as a fbsql resource
163      * identifier.
164      *
165      * @param the SQL query
166      *
167      * @access public
168      *
169      * @return mixed returns a valid fbsql result for successful SELECT
170      * queries, DB_OK for other successful queries.  A DB error is
171      * returned on failure.
172      */
173     function simpleQuery($query)
174     {
175         $this->last_query = $query;
176         $query = $this->modifyQuery($query);
177         $result = @fbsql_query("$query;", $this->connection);
178         if (!$result) {
179             return $this->fbsqlRaiseError();
180         }
181         // Determine which queries that should return data, and which
182         // should return an error code only.
183         if (DB::isManip($query)) {
184             return DB_OK;
185         }
186         $numrows = $this->numrows($result);
187         if (is_object($numrows)) {
188             return $numrows;
189         }
190         $this->num_rows[$result] = $numrows;
191         return $result;
192     }
193
194     // }}}
195     // {{{ nextResult()
196
197     /**
198      * Move the internal fbsql result pointer to the next available result
199      *
200      * @param a valid fbsql result resource
201      *
202      * @access public
203      *
204      * @return true if a result is available otherwise return false
205      */
206     function nextResult($result)
207     {
208         return @fbsql_next_result($result);
209     }
210
211     // }}}
212     // {{{ fetchInto()
213
214     /**
215      * Fetch a row and insert the data into an existing array.
216      *
217      * Formating of the array and the data therein are configurable.
218      * See DB_result::fetchInto() for more information.
219      *
220      * @param resource $result query result identifier
221      * @param array    $arr    (reference) array where data from the row
222      *                            should be placed
223      * @param int $fetchmode how the resulting array should be indexed
224      * @param int $rownum    the row number to fetch
225      *
226      * @return mixed DB_OK on success, null when end of result set is
227      *               reached or on failure
228      *
229      * @see DB_result::fetchInto()
230      * @access private
231      */
232     function fetchInto($result, &$arr, $fetchmode, $rownum=null)
233     {
234         if ($rownum !== null) {
235             if (!@fbsql_data_seek($result, $rownum)) {
236                 return null;
237             }
238         }
239         if ($fetchmode & DB_FETCHMODE_ASSOC) {
240             $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
241             if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
242                 $arr = array_change_key_case($arr, CASE_LOWER);
243             }
244         } else {
245             $arr = @fbsql_fetch_row($result);
246         }
247         if (!$arr) {
248             $errno = @fbsql_errno($this->connection);
249             if (!$errno) {
250                 return null;
251             }
252             return $this->fbsqlRaiseError($errno);
253         }
254         if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
255             $this->_rtrimArrayValues($arr);
256         }
257         if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
258             $this->_convertNullArrayValuesToEmpty($arr);
259         }
260         return DB_OK;
261     }
262
263     // }}}
264     // {{{ freeResult()
265
266     /**
267      * Free the internal resources associated with $result.
268      *
269      * @param $result fbsql result identifier
270      *
271      * @access public
272      *
273      * @return bool true on success, false if $result is invalid
274      */
275     function freeResult($result)
276     {
277         return @fbsql_free_result($result);
278     }
279
280     // }}}
281     // {{{ autoCommit()
282
283     function autoCommit($onoff=false)
284     {
285         if ($onoff) {
286             $this->query("SET COMMIT TRUE");
287         } else {
288             $this->query("SET COMMIT FALSE");
289         }
290     }
291
292     // }}}
293     // {{{ commit()
294
295     function commit()
296     {
297         @fbsql_commit();
298     }
299
300     // }}}
301     // {{{ rollback()
302
303     function rollback()
304     {
305         @fbsql_rollback();
306     }
307
308     // }}}
309     // {{{ numCols()
310
311     /**
312      * Get the number of columns in a result set.
313      *
314      * @param $result fbsql result identifier
315      *
316      * @access public
317      *
318      * @return int the number of columns per row in $result
319      */
320     function numCols($result)
321     {
322         $cols = @fbsql_num_fields($result);
323
324         if (!$cols) {
325             return $this->fbsqlRaiseError();
326         }
327
328         return $cols;
329     }
330
331     // }}}
332     // {{{ numRows()
333
334     /**
335      * Get the number of rows in a result set.
336      *
337      * @param $result fbsql result identifier
338      *
339      * @access public
340      *
341      * @return int the number of rows in $result
342      */
343     function numRows($result)
344     {
345         $rows = @fbsql_num_rows($result);
346         if ($rows === null) {
347             return $this->fbsqlRaiseError();
348         }
349         return $rows;
350     }
351
352     // }}}
353     // {{{ affectedRows()
354
355     /**
356      * Gets the number of rows affected by the data manipulation
357      * query.  For other queries, this function returns 0.
358      *
359      * @return number of rows affected by the last query
360      */
361     function affectedRows()
362     {
363         if (DB::isManip($this->last_query)) {
364             $result = @fbsql_affected_rows($this->connection);
365         } else {
366             $result = 0;
367         }
368         return $result;
369      }
370
371     // }}}
372     // {{{ errorNative()
373
374     /**
375      * Get the native error code of the last error (if any) that
376      * occured on the current connection.
377      *
378      * @access public
379      *
380      * @return int native fbsql error code
381      */
382     function errorNative()
383     {
384         return @fbsql_errno($this->connection);
385     }
386
387     // }}}
388     // {{{ nextId()
389
390     /**
391      * Returns the next free id in a sequence
392      *
393      * @param string  $seq_name name of the sequence
394      * @param boolean $ondemand when true, the seqence is automatically
395      *                           created if it does not exist
396      *
397      * @return int the next id number in the sequence.  DB_Error if problem.
398      *
399      * @internal
400      * @see DB_common::nextID()
401      * @access public
402      */
403     function nextId($seq_name, $ondemand = true)
404     {
405         $seqname = $this->getSequenceName($seq_name);
406         $repeat = 0;
407         do {
408             $result = $this->query("INSERT INTO ${seqname} VALUES(NULL)");
409             if ($ondemand && DB::isError($result) &&
410                 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
411                 $repeat = 1;
412                 $result = $this->createSequence($seq_name);
413                 if (DB::isError($result)) {
414                     return $result;
415                 }
416             } else {
417                 $repeat = 0;
418             }
419         } while ($repeat);
420         if (DB::isError($result)) {
421             return $result;
422         }
423         return @fbsql_insert_id($this->connection);
424     }
425
426     /**
427      * Creates a new sequence
428      *
429      * @param string $seq_name name of the new sequence
430      *
431      * @return int DB_OK on success.  A DB_Error object is returned if
432      *              problems arise.
433      *
434      * @internal
435      * @see DB_common::createSequence()
436      * @access public
437      */
438     function createSequence($seq_name)
439     {
440         $seqname = $this->getSequenceName($seq_name);
441         return $this->query("CREATE TABLE ${seqname} ".
442                             '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
443                             ' PRIMARY KEY(id))');
444     }
445
446     // }}}
447     // {{{ dropSequence()
448
449     /**
450      * Deletes a sequence
451      *
452      * @param string $seq_name name of the sequence to be deleted
453      *
454      * @return int DB_OK on success.  DB_Error if problems.
455      *
456      * @internal
457      * @see DB_common::dropSequence()
458      * @access public
459      */
460     function dropSequence($seq_name)
461     {
462         $seqname = $this->getSequenceName($seq_name);
463         return $this->query("DROP TABLE ${seqname} RESTRICT");
464     }
465
466     // }}}
467     // {{{ modifyQuery()
468
469     function modifyQuery($query)
470     {
471         if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) {
472             // "DELETE FROM table" gives 0 affected rows in fbsql.
473             // This little hack lets you know how many rows were deleted.
474             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
475                 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
476                                       'DELETE FROM \1 WHERE 1=1', $query);
477             }
478         }
479         return $query;
480     }
481
482     // }}}
483     // {{{ quoteSmart()
484
485     /**
486      * Format input so it can be safely used in a query
487      *
488      * @param mixed $in data to be quoted
489      *
490      * @return mixed Submitted variable's type = returned value:
491      *               + null = the string <samp>NULL</samp>
492      *               + boolean = string <samp>TRUE</samp> or <samp>FALSE</samp>
493      *               + integer or double = the unquoted number
494      *               + other (including strings and numeric strings) =
495      *                 the data escaped according to MySQL's settings
496      *                 then encapsulated between single quotes
497      *
498      * @internal
499      */
500     function quoteSmart($in)
501     {
502         if (is_int($in) || is_double($in)) {
503             return $in;
504         } elseif (is_bool($in)) {
505             return $in ? 'TRUE' : 'FALSE';
506         } elseif (is_null($in)) {
507             return 'NULL';
508         } else {
509             return "'" . $this->escapeSimple($in) . "'";
510         }
511     }
512
513     // }}}
514     // {{{ fbsqlRaiseError()
515
516     /**
517      * Gather information about an error, then use that info to create a
518      * DB error object and finally return that object.
519      *
520      * @param integer $errno PEAR error number (usually a DB constant) if
521      *                          manually raising an error
522      * @return object DB error object
523      * @see DB_common::errorCode()
524      * @see DB_common::raiseError()
525      */
526     function fbsqlRaiseError($errno = null)
527     {
528         if ($errno === null) {
529             $errno = $this->errorCode(fbsql_errno($this->connection));
530         }
531         return $this->raiseError($errno, null, null, null,
532                         @fbsql_error($this->connection));
533     }
534
535     // }}}
536     // {{{ tableInfo()
537
538     /**
539      * Returns information about a table or a result set.
540      *
541      * @param object|string $result DB_result object from a query or a
542      *                                string containing the name of a table
543      * @param  int   $mode a valid tableInfo mode
544      * @return array an associative array with the information requested
545      *                or an error object if something is wrong
546      * @access public
547      * @internal
548      * @see DB_common::tableInfo()
549      */
550     function tableInfo($result, $mode = null) {
551         if (isset($result->result)) {
552             /*
553              * Probably received a result object.
554              * Extract the result resource identifier.
555              */
556             $id = $result->result;
557             $got_string = false;
558         } elseif (is_string($result)) {
559             /*
560              * Probably received a table name.
561              * Create a result resource identifier.
562              */
563             $id = @fbsql_list_fields($this->dsn['database'],
564                                      $result, $this->connection);
565             $got_string = true;
566         } else {
567             /*
568              * Probably received a result resource identifier.
569              * Copy it.
570              * Depricated.  Here for compatibility only.
571              */
572             $id = $result;
573             $got_string = false;
574         }
575
576         if (!is_resource($id)) {
577             return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
578         }
579
580         if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
581             $case_func = 'strtolower';
582         } else {
583             $case_func = 'strval';
584         }
585
586         $count = @fbsql_num_fields($id);
587
588         // made this IF due to performance (one if is faster than $count if's)
589         if (!$mode) {
590             for ($i=0; $i<$count; $i++) {
591                 $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
592                 $res[$i]['name']  = $case_func(@fbsql_field_name($id, $i));
593                 $res[$i]['type']  = @fbsql_field_type($id, $i);
594                 $res[$i]['len']   = @fbsql_field_len($id, $i);
595                 $res[$i]['flags'] = @fbsql_field_flags($id, $i);
596             }
597         } else { // full
598             $res["num_fields"]= $count;
599
600             for ($i=0; $i<$count; $i++) {
601                 $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i));
602                 $res[$i]['name']  = $case_func(@fbsql_field_name($id, $i));
603                 $res[$i]['type']  = @fbsql_field_type($id, $i);
604                 $res[$i]['len']   = @fbsql_field_len($id, $i);
605                 $res[$i]['flags'] = @fbsql_field_flags($id, $i);
606
607                 if ($mode & DB_TABLEINFO_ORDER) {
608                     $res['order'][$res[$i]['name']] = $i;
609                 }
610                 if ($mode & DB_TABLEINFO_ORDERTABLE) {
611                     $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
612                 }
613             }
614         }
615
616         // free the result only if we were called on a table
617         if ($got_string) {
618             @fbsql_free_result($id);
619         }
620         return $res;
621     }
622
623     // }}}
624     // {{{ getSpecialQuery()
625
626     /**
627      * Returns the query needed to get some backend info
628      * @param  string $type What kind of info you want to retrieve
629      * @return string The SQL query string
630      */
631     function getSpecialQuery($type)
632     {
633         switch ($type) {
634             case 'tables':
635                 return 'select "table_name" from information_schema.tables';
636             default:
637                 return null;
638         }
639     }
640
641     // }}}
642 }
643
644 /*
645  * Local variables:
646  * tab-width: 4
647  * c-basic-offset: 4
648  * End:
649  */
650
651 ?>