]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/DB/fbsql.php
new PEAR DB 1.3 backends plus the experimental PEAR DB_Pager
[SourceForge/phpwiki.git] / lib / pear / DB / fbsql.php
1 <?php
2 //
3 // +----------------------------------------------------------------------+
4 // | PHP Version 4                                                        |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2002 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 // +----------------------------------------------------------------------+
18 //
19 // $Id: fbsql.php,v 1.1 2002-09-12 11:47:07 rurban Exp $
20 //
21 // Database independent query interface definition for PHP's FrontBase
22 // extension.
23 //
24 // Based on DB 1.3 from the pear.php.net repository. 
25 // The only modifications made have been modification of the include paths. 
26 //
27 rcs_id('$Id: fbsql.php,v 1.1 2002-09-12 11:47:07 rurban Exp $');
28 rcs_id('From Pear CVS: Id: fbsql.php,v 1.3 2002/05/09 12:29:53 ssb Exp');
29
30 //
31 // XXX legend:
32 //
33 // XXX ERRORMSG: The error message from the fbsql function should
34 //               be registered here.
35 //
36
37 require_once 'lib/pear/DB/common.php';
38
39 class DB_fbsql extends DB_common
40 {
41     // {{{ properties
42
43     var $connection;
44     var $phptype, $dbsyntax;
45     var $prepare_tokens = array();
46     var $prepare_types = array();
47     var $num_rows = array();
48     var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */
49
50     // }}}
51     // {{{ constructor
52
53     /**
54      * DB_fbsql constructor.
55      *
56      * @access public
57      */
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
90     // {{{ connect()
91
92     /**
93      * Connect to a database and log in as the specified user.
94      *
95      * @param $dsn the data source name (see DB::parseDSN for syntax)
96      * @param $persistent (optional) whether the connection should
97      *        be persistent
98      * @access public
99      * @return int DB_OK on success, a DB error on failure
100      */
101
102     function connect($dsninfo, $persistent = false)
103     {
104         if (!DB::assertExtension('fbsql'))
105             return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
106
107         $this->dsn = $dsninfo;
108         $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
109         $user = $dsninfo['username'];
110         $pw = $dsninfo['password'];
111
112         $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
113
114         ini_set('track_errors', true);
115         if ($dbhost && $user && $pw) {
116             $conn = @$connect_function($dbhost, $user, $pw);
117         } elseif ($dbhost && $user) {
118             $conn = @$connect_function($dbhost, $user);
119         } elseif ($dbhost) {
120             $conn = @$connect_function($dbhost);
121         } else {
122             $conn = false;
123         }
124         ini_restore("track_errors");
125         if (empty($conn)) {
126             if (empty($php_errormsg)) {
127                 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
128             } else {
129                 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
130                                          null, $php_errormsg);
131             }
132         }
133
134         if ($dsninfo['database']) {
135             if (!fbsql_select_db($dsninfo['database'], $conn)) {
136                 return $this->fbsqlRaiseError();
137             }
138         }
139
140         $this->connection = $conn;
141         return DB_OK;
142     }
143
144     // }}}
145     // {{{ disconnect()
146
147     /**
148      * Log out and disconnect from the database.
149      *
150      * @access public
151      *
152      * @return bool TRUE on success, FALSE if not connected.
153      */
154     function disconnect()
155     {
156         $ret = fbsql_close($this->connection);
157         $this->connection = null;
158         return $ret;
159     }
160
161     // }}}
162     // {{{ simpleQuery()
163
164     /**
165      * Send a query to fbsql and return the results as a fbsql resource
166      * identifier.
167      *
168      * @param the SQL query
169      *
170      * @access public
171      *
172      * @return mixed returns a valid fbsql result for successful SELECT
173      * queries, DB_OK for other successful queries.  A DB error is
174      * returned on failure.
175      */
176     function simpleQuery($query)
177     {
178         $this->last_query = $query;
179         $query = $this->modifyQuery($query);
180         $result = @fbsql_query("$query;", $this->connection);
181         if (!$result) {
182             return $this->fbsqlRaiseError();
183         }
184         // Determine which queries that should return data, and which
185         // should return an error code only.
186         if (DB::isManip($query)) {
187             return DB_OK;
188         }
189         $numrows = $this->numrows($result);
190         if (is_object($numrows)) {
191             return $numrows;
192         }
193         $this->num_rows[$result] = $numrows;
194         return $result;
195     }
196
197     // }}}
198     // {{{ nextResult()
199
200     /**
201      * Move the internal fbsql result pointer to the next available result
202      *
203      * @param a valid fbsql result resource
204      *
205      * @access public
206      *
207      * @return true if a result is available otherwise return false
208      */
209     function nextResult($result)
210     {
211         return @fbsql_next_result($result);
212     }
213
214     // }}}
215     // {{{ fetchRow()
216
217     /**
218      * Fetch and return a row of data (it uses fetchInto for that)
219      * @param $result fbsql result identifier
220      * @param   $fetchmode  format of fetched row array
221      * @param   $rownum     the absolute row number to fetch
222      *
223      * @return  array   a row of data, or false on error
224      */
225     function fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
226     {
227         if ($fetchmode == DB_FETCHMODE_DEFAULT) {
228             $fetchmode = $this->fetchmode;
229         }
230         $res = $this->fetchInto ($result, $arr, $fetchmode, $rownum);
231         if ($res !== DB_OK) {
232             return $res;
233         }
234         return $arr;
235     }
236
237     // }}}
238     // {{{ fetchInto()
239
240     /**
241      * Fetch a row and insert the data into an existing array.
242      *
243      * @param $result fbsql result identifier
244      * @param $arr (reference) array where data from the row is stored
245      * @param $fetchmode how the array data should be indexed
246      * @param   $rownum the row number to fetch
247      * @access public
248      *
249      * @return int DB_OK on success, a DB error on failure
250      */
251     function fetchInto($result, &$arr, $fetchmode, $rownum=null)
252     {
253         if ($rownum !== null) {
254             if (!@fbsql_data_seek($result, $rownum)) {
255                 return null;
256             }
257         }
258         if ($fetchmode & DB_FETCHMODE_ASSOC) {
259             $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
260         } else {
261             $arr = @fbsql_fetch_row($result);
262         }
263         if (!$arr) {
264             $errno = @fbsql_errno($this->connection);
265             if (!$errno) {
266                 return NULL;
267             }
268             return $this->fbsqlRaiseError($errno);
269         }
270         return DB_OK;
271     }
272
273     // }}}
274     // {{{ freeResult()
275
276     /**
277      * Free the internal resources associated with $result.
278      *
279      * @param $result fbsql result identifier or DB statement identifier
280      *
281      * @access public
282      *
283      * @return bool TRUE on success, FALSE if $result is invalid
284      */
285     function freeResult($result)
286     {
287         if (is_resource($result)) {
288             return fbsql_free_result($result);
289         }
290
291         if (!isset($this->prepare_tokens[(int)$result])) {
292             return false;
293         }
294
295         unset($this->prepare_tokens[(int)$result]);
296         unset($this->prepare_types[(int)$result]);
297
298         return true;
299     }
300
301     // }}}
302     // {{{ autoCommit()
303
304     function autoCommit($onoff=false)
305     {
306         if ($onoff) {
307             $this->query("SET COMMIT TRUE");
308         } else {
309             $this->query("SET COMMIT FALSE");
310         }
311     }
312
313     // }}}
314     // {{{ commit()
315
316     function commit()
317     {
318         fbsql_commit();
319     }
320
321     // }}}
322     // {{{ rollback()
323
324     function rollback()
325     {
326         fbsql_rollback();
327     }
328
329     // }}}
330     // {{{ numCols()
331
332     /**
333      * Get the number of columns in a result set.
334      *
335      * @param $result fbsql result identifier
336      *
337      * @access public
338      *
339      * @return int the number of columns per row in $result
340      */
341     function numCols($result)
342     {
343         $cols = @fbsql_num_fields($result);
344
345         if (!$cols) {
346             return $this->fbsqlRaiseError();
347         }
348
349         return $cols;
350     }
351
352     // }}}
353     // {{{ numRows()
354
355     /**
356      * Get the number of rows in a result set.
357      *
358      * @param $result fbsql result identifier
359      *
360      * @access public
361      *
362      * @return int the number of rows in $result
363      */
364     function numRows($result)
365     {
366         $rows = @fbsql_num_rows($result);
367         if ($rows === null) {
368             return $this->fbsqlRaiseError();
369         }
370         return $rows;
371     }
372
373     // }}}
374     // {{{ affectedRows()
375
376     /**
377      * Gets the number of rows affected by the data manipulation
378      * query.  For other queries, this function returns 0.
379      *
380      * @return number of rows affected by the last query
381      */
382
383     function affectedRows()
384     {
385         if (DB::isManip($this->last_query)) {
386             $result = @fbsql_affected_rows($this->connection);
387         } else {
388             $result = 0;
389         }
390         return $result;
391      }
392
393     // }}}
394     // {{{ errorNative()
395
396     /**
397      * Get the native error code of the last error (if any) that
398      * occured on the current connection.
399      *
400      * @access public
401      *
402      * @return int native fbsql error code
403      */
404
405     function errorNative()
406     {
407         return fbsql_errno($this->connection);
408     }
409
410     // }}}
411     // {{{ nextId()
412
413     /**
414      * Get the next value in a sequence.  We emulate sequences
415      * for fbsql.  Will create the sequence if it does not exist.
416      *
417      * @access public
418      *
419      * @param $seq_name the name of the sequence
420      *
421      * @param $ondemand whether to create the sequence table on demand
422      * (default is true)
423      *
424      * @return a sequence integer, or a DB error
425      */
426     function nextId($seq_name, $ondemand = true)
427     {
428         $sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
429         $repeat = 0;
430         do {
431             $seqname = sprintf($this->getOption("seqname_format"), $sqn);
432             $result = $this->query("INSERT INTO ${seqname} VALUES(NULL)");
433             if ($ondemand && DB::isError($result) &&
434                 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
435                 $repeat = 1;
436                 $result = $this->createSequence($seq_name);
437                 if (DB::isError($result)) {
438                     return $result;
439                 }
440             } else {
441                 $repeat = 0;
442             }
443         } while ($repeat);
444         if (DB::isError($result)) {
445             return $result;
446         }
447         return fbsql_insert_id($this->connection);
448     }
449
450     // }}}
451     // {{{ createSequence()
452
453     function createSequence($seq_name)
454     {
455         $sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
456         $seqname = sprintf($this->getOption("seqname_format"), $sqn);
457         return $this->query("CREATE TABLE ${seqname} ".
458                             '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'.
459                             ' PRIMARY KEY(id))');
460     }
461
462     // }}}
463     // {{{ dropSequence()
464
465     function dropSequence($seq_name)
466     {
467         $sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
468         $seqname = sprintf($this->getOption("seqname_format"), $sqn);
469         return $this->query("DROP TABLE ${seqname} RESTRICT");
470     }
471
472     // }}}
473     // {{{ modifyQuery()
474
475     function modifyQuery($query)
476     {
477         if ($this->options['optimize'] == 'portability') {
478             // "DELETE FROM table" gives 0 affected rows in fbsql.
479             // This little hack lets you know how many rows were deleted.
480             if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
481                 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
482                                       'DELETE FROM \1 WHERE 1=1', $query);
483             }
484         }
485         return $query;
486     }
487
488     // }}}
489     // {{{ fbsqlRaiseError()
490
491     function fbsqlRaiseError($errno = null)
492     {
493         if ($errno === null) {
494             $errno = $this->errorCode(fbsql_errno($this->connection));
495         }
496         return $this->raiseError($errno, null, null, null,
497                         fbsql_error($this->connection));
498     }
499
500     // }}}
501     // {{{ tableInfo()
502
503     function tableInfo($result, $mode = null) {
504         $count = 0;
505         $id    = 0;
506         $res   = array();
507
508         /*
509          * depending on $mode, metadata returns the following values:
510          *
511          * - mode is false (default):
512          * $result[]:
513          *   [0]["table"]  table name
514          *   [0]["name"]   field name
515          *   [0]["type"]   field type
516          *   [0]["len"]    field length
517          *   [0]["flags"]  field flags
518          *
519          * - mode is DB_TABLEINFO_ORDER
520          * $result[]:
521          *   ["num_fields"] number of metadata records
522          *   [0]["table"]  table name
523          *   [0]["name"]   field name
524          *   [0]["type"]   field type
525          *   [0]["len"]    field length
526          *   [0]["flags"]  field flags
527          *   ["order"][field name]  index of field named "field name"
528          *   The last one is used, if you have a field name, but no index.
529          *   Test:  if (isset($result['meta']['myfield'])) { ...
530          *
531          * - mode is DB_TABLEINFO_ORDERTABLE
532          *    the same as above. but additionally
533          *   ["ordertable"][table name][field name] index of field
534          *      named "field name"
535          *
536          *      this is, because if you have fields from different
537          *      tables with the same field name * they override each
538          *      other with DB_TABLEINFO_ORDER
539          *
540          *      you can combine DB_TABLEINFO_ORDER and
541          *      DB_TABLEINFO_ORDERTABLE with DB_TABLEINFO_ORDER |
542          *      DB_TABLEINFO_ORDERTABLE * or with DB_TABLEINFO_FULL
543          */
544
545         // if $result is a string, then we want information about a
546         // table without a resultset
547         if (is_string($result)) {
548             $id = @fbsql_list_fields($this->dsn['database'],
549                                      $result, $this->connection);
550             if (empty($id)) {
551                 return $this->fbsqlRaiseError();
552             }
553         } else { // else we want information about a resultset
554             $id = $result;
555             if (empty($id)) {
556                 return $this->fbsqlRaiseError();
557             }
558         }
559
560         $count = @fbsql_num_fields($id);
561
562         // made this IF due to performance (one if is faster than $count if's)
563         if (empty($mode)) {
564             for ($i=0; $i<$count; $i++) {
565                 $res[$i]['table'] = @fbsql_field_table ($id, $i);
566                 $res[$i]['name']  = @fbsql_field_name  ($id, $i);
567                 $res[$i]['type']  = @fbsql_field_type  ($id, $i);
568                 $res[$i]['len']   = @fbsql_field_len   ($id, $i);
569                 $res[$i]['flags'] = @fbsql_field_flags ($id, $i);
570             }
571         } else { // full
572             $res["num_fields"]= $count;
573
574             for ($i=0; $i<$count; $i++) {
575                 $res[$i]['table'] = @fbsql_field_table ($id, $i);
576                 $res[$i]['name']  = @fbsql_field_name  ($id, $i);
577                 $res[$i]['type']  = @fbsql_field_type  ($id, $i);
578                 $res[$i]['len']   = @fbsql_field_len   ($id, $i);
579                 $res[$i]['flags'] = @fbsql_field_flags ($id, $i);
580                 if ($mode & DB_TABLEINFO_ORDER) {
581                     $res['order'][$res[$i]['name']] = $i;
582                 }
583                 if ($mode & DB_TABLEINFO_ORDERTABLE) {
584                     $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
585                 }
586             }
587         }
588
589         // free the result only if we were called on a table
590         if (is_string($result)) {
591             @fbsql_free_result($id);
592         }
593         return $res;
594     }
595
596     // }}}
597     // {{{ getSpecialQuery()
598
599     /**
600     * Returns the query needed to get some backend info
601     * @param string $type What kind of info you want to retrieve
602     * @return string The SQL query string
603     */
604     function getSpecialQuery($type)
605     {
606         switch ($type) {
607             case 'tables':
608                 $sql = 'select "table_name" from information_schema.tables';
609                 break;
610             default:
611                 return null;
612         }
613         return $sql;
614     }
615
616     // }}}
617 }
618
619 // TODO/wishlist:
620 // longReadlen
621 // binmode
622
623 ?>