3 // +----------------------------------------------------------------------+
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 // +----------------------------------------------------------------------+
19 // $Id: fbsql.php,v 1.2 2004-04-26 20:44:37 rurban Exp $
21 // Database independent query interface definition for PHP's FrontBase
24 // Based on DB 1.3 from the pear.php.net repository.
25 // The only modifications made have been modification of the include paths.
27 rcs_id('$Id: fbsql.php,v 1.2 2004-04-26 20:44:37 rurban Exp $');
28 rcs_id('From Pear CVS: Id: fbsql.php,v 1.3 2002/05/09 12:29:53 ssb Exp');
33 // XXX ERRORMSG: The error message from the fbsql function should
34 // be registered here.
37 require_once 'DB/common.php';
39 class DB_fbsql extends DB_common
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 */
54 * DB_fbsql constructor.
62 $this->phptype = 'fbsql';
63 $this->dbsyntax = 'fbsql';
64 $this->features = array(
67 'transactions' => true,
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,
93 * Connect to a database and log in as the specified user.
95 * @param $dsn the data source name (see DB::parseDSN for syntax)
96 * @param $persistent (optional) whether the connection should
99 * @return int DB_OK on success, a DB error on failure
102 function connect($dsninfo, $persistent = false)
104 if (!DB::assertExtension('fbsql'))
105 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
107 $this->dsn = $dsninfo;
108 $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
109 $user = $dsninfo['username'];
110 $pw = $dsninfo['password'];
112 $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
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);
120 $conn = @$connect_function($dbhost);
124 ini_restore("track_errors");
126 if (empty($php_errormsg)) {
127 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
129 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
130 null, $php_errormsg);
134 if ($dsninfo['database']) {
135 if (!fbsql_select_db($dsninfo['database'], $conn)) {
136 return $this->fbsqlRaiseError();
140 $this->connection = $conn;
148 * Log out and disconnect from the database.
152 * @return bool TRUE on success, FALSE if not connected.
154 function disconnect()
156 $ret = fbsql_close($this->connection);
157 $this->connection = null;
165 * Send a query to fbsql and return the results as a fbsql resource
168 * @param the SQL query
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.
176 function simpleQuery($query)
178 $this->last_query = $query;
179 $query = $this->modifyQuery($query);
180 $result = @fbsql_query("$query;", $this->connection);
182 return $this->fbsqlRaiseError();
184 // Determine which queries that should return data, and which
185 // should return an error code only.
186 if (DB::isManip($query)) {
189 $numrows = $this->numrows($result);
190 if (is_object($numrows)) {
193 $this->num_rows[$result] = $numrows;
201 * Move the internal fbsql result pointer to the next available result
203 * @param a valid fbsql result resource
207 * @return true if a result is available otherwise return false
209 function nextResult($result)
211 return @fbsql_next_result($result);
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
223 * @return array a row of data, or false on error
225 function fetchRow($result, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null)
227 if ($fetchmode == DB_FETCHMODE_DEFAULT) {
228 $fetchmode = $this->fetchmode;
230 $res = $this->fetchInto ($result, $arr, $fetchmode, $rownum);
231 if ($res !== DB_OK) {
241 * Fetch a row and insert the data into an existing array.
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
249 * @return int DB_OK on success, a DB error on failure
251 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
253 if ($rownum !== null) {
254 if (!@fbsql_data_seek($result, $rownum)) {
258 if ($fetchmode & DB_FETCHMODE_ASSOC) {
259 $arr = @fbsql_fetch_array($result, FBSQL_ASSOC);
261 $arr = @fbsql_fetch_row($result);
264 $errno = @fbsql_errno($this->connection);
268 return $this->fbsqlRaiseError($errno);
277 * Free the internal resources associated with $result.
279 * @param $result fbsql result identifier or DB statement identifier
283 * @return bool TRUE on success, FALSE if $result is invalid
285 function freeResult($result)
287 if (is_resource($result)) {
288 return fbsql_free_result($result);
291 if (!isset($this->prepare_tokens[(int)$result])) {
295 unset($this->prepare_tokens[(int)$result]);
296 unset($this->prepare_types[(int)$result]);
304 function autoCommit($onoff=false)
307 $this->query("SET COMMIT TRUE");
309 $this->query("SET COMMIT FALSE");
333 * Get the number of columns in a result set.
335 * @param $result fbsql result identifier
339 * @return int the number of columns per row in $result
341 function numCols($result)
343 $cols = @fbsql_num_fields($result);
346 return $this->fbsqlRaiseError();
356 * Get the number of rows in a result set.
358 * @param $result fbsql result identifier
362 * @return int the number of rows in $result
364 function numRows($result)
366 $rows = @fbsql_num_rows($result);
367 if ($rows === null) {
368 return $this->fbsqlRaiseError();
374 // {{{ affectedRows()
377 * Gets the number of rows affected by the data manipulation
378 * query. For other queries, this function returns 0.
380 * @return number of rows affected by the last query
383 function affectedRows()
385 if (DB::isManip($this->last_query)) {
386 $result = @fbsql_affected_rows($this->connection);
397 * Get the native error code of the last error (if any) that
398 * occured on the current connection.
402 * @return int native fbsql error code
405 function errorNative()
407 return fbsql_errno($this->connection);
414 * Get the next value in a sequence. We emulate sequences
415 * for fbsql. Will create the sequence if it does not exist.
419 * @param $seq_name the name of the sequence
421 * @param $ondemand whether to create the sequence table on demand
424 * @return a sequence integer, or a DB error
426 function nextId($seq_name, $ondemand = true)
428 $sqn = preg_replace('/[^a-z0-9_]/i', '_', $seq_name);
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) {
436 $result = $this->createSequence($seq_name);
437 if (DB::isError($result)) {
444 if (DB::isError($result)) {
447 return fbsql_insert_id($this->connection);
451 // {{{ createSequence()
453 function createSequence($seq_name)
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))');
463 // {{{ dropSequence()
465 function dropSequence($seq_name)
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");
475 function modifyQuery($query)
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);
489 // {{{ fbsqlRaiseError()
491 function fbsqlRaiseError($errno = null)
493 if ($errno === null) {
494 $errno = $this->errorCode(fbsql_errno($this->connection));
496 return $this->raiseError($errno, null, null, null,
497 fbsql_error($this->connection));
503 function tableInfo($result, $mode = null) {
509 * depending on $mode, metadata returns the following values:
511 * - mode is false (default):
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
519 * - mode is DB_TABLEINFO_ORDER
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'])) { ...
531 * - mode is DB_TABLEINFO_ORDERTABLE
532 * the same as above. but additionally
533 * ["ordertable"][table name][field name] index of field
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
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
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);
551 return $this->fbsqlRaiseError();
553 } else { // else we want information about a resultset
556 return $this->fbsqlRaiseError();
560 $count = @fbsql_num_fields($id);
562 // made this IF due to performance (one if is faster than $count if's)
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);
572 $res["num_fields"]= $count;
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;
583 if ($mode & DB_TABLEINFO_ORDERTABLE) {
584 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
589 // free the result only if we were called on a table
590 if (is_string($result)) {
591 @fbsql_free_result($id);
597 // {{{ getSpecialQuery()
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
604 function getSpecialQuery($type)
608 $sql = 'select "table_name" from information_schema.tables';