2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
3 // +----------------------------------------------------------------------+
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 // +----------------------------------------------------------------------+
22 // XXX ERRORMSG: The error message from the fbsql function should
23 // be registered here.
29 require_once 'DB/common.php';
32 * Database independent query interface definition for PHP's FrontBase
38 * @author Frank M. Kromann <frank@frontbase.com>
40 class DB_fbsql extends DB_common
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 */
55 * 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,
92 * Connect to a database and log in as the specified user.
94 * @param $dsn the data source name (see DB::parseDSN for syntax)
95 * @param $persistent (optional) whether the connection should
98 * @return int DB_OK on success, a DB error on failure
100 function connect($dsninfo, $persistent = false)
102 if (!DB::assertExtension('fbsql')) {
103 return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
106 $this->dsn = $dsninfo;
107 $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost';
110 $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect';
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']);
118 $conn = @$connect_function($dbhost);
123 if (empty($php_errormsg)) {
124 return $this->raiseError(DB_ERROR_CONNECT_FAILED);
126 return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null,
127 null, $php_errormsg);
131 if ($dsninfo['database']) {
132 if (!fbsql_select_db($dsninfo['database'], $conn)) {
133 return $this->fbsqlRaiseError();
137 $this->connection = $conn;
145 * Log out and disconnect from the database.
149 * @return bool true on success, false if not connected.
151 function disconnect()
153 $ret = @fbsql_close($this->connection);
154 $this->connection = null;
162 * Send a query to fbsql and return the results as a fbsql resource
165 * @param the SQL query
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.
173 function simpleQuery($query)
175 $this->last_query = $query;
176 $query = $this->modifyQuery($query);
177 $result = @fbsql_query("$query;", $this->connection);
179 return $this->fbsqlRaiseError();
181 // Determine which queries that should return data, and which
182 // should return an error code only.
183 if (DB::isManip($query)) {
186 $numrows = $this->numrows($result);
187 if (is_object($numrows)) {
190 $this->num_rows[$result] = $numrows;
198 * Move the internal fbsql result pointer to the next available result
200 * @param a valid fbsql result resource
204 * @return true if a result is available otherwise return false
206 function nextResult($result)
208 return @fbsql_next_result($result);
215 * Fetch a row and insert the data into an existing array.
217 * Formating of the array and the data therein are configurable.
218 * See DB_result::fetchInto() for more information.
220 * @param resource $result query result identifier
221 * @param array $arr (reference) array where data from the row
223 * @param int $fetchmode how the resulting array should be indexed
224 * @param int $rownum the row number to fetch
226 * @return mixed DB_OK on success, null when end of result set is
227 * reached or on failure
229 * @see DB_result::fetchInto()
232 function fetchInto($result, &$arr, $fetchmode, $rownum=null)
234 if ($rownum !== null) {
235 if (!@fbsql_data_seek($result, $rownum)) {
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);
245 $arr = @fbsql_fetch_row($result);
248 $errno = @fbsql_errno($this->connection);
252 return $this->fbsqlRaiseError($errno);
254 if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
255 $this->_rtrimArrayValues($arr);
257 if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
258 $this->_convertNullArrayValuesToEmpty($arr);
267 * Free the internal resources associated with $result.
269 * @param $result fbsql result identifier
273 * @return bool true on success, false if $result is invalid
275 function freeResult($result)
277 return @fbsql_free_result($result);
283 function autoCommit($onoff=false)
286 $this->query("SET COMMIT TRUE");
288 $this->query("SET COMMIT FALSE");
312 * Get the number of columns in a result set.
314 * @param $result fbsql result identifier
318 * @return int the number of columns per row in $result
320 function numCols($result)
322 $cols = @fbsql_num_fields($result);
325 return $this->fbsqlRaiseError();
335 * Get the number of rows in a result set.
337 * @param $result fbsql result identifier
341 * @return int the number of rows in $result
343 function numRows($result)
345 $rows = @fbsql_num_rows($result);
346 if ($rows === null) {
347 return $this->fbsqlRaiseError();
353 // {{{ affectedRows()
356 * Gets the number of rows affected by the data manipulation
357 * query. For other queries, this function returns 0.
359 * @return number of rows affected by the last query
361 function affectedRows()
363 if (DB::isManip($this->last_query)) {
364 $result = @fbsql_affected_rows($this->connection);
375 * Get the native error code of the last error (if any) that
376 * occured on the current connection.
380 * @return int native fbsql error code
382 function errorNative()
384 return @fbsql_errno($this->connection);
391 * Returns the next free id in a sequence
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
397 * @return int the next id number in the sequence. DB_Error if problem.
400 * @see DB_common::nextID()
403 function nextId($seq_name, $ondemand = true)
405 $seqname = $this->getSequenceName($seq_name);
408 $result = $this->query("INSERT INTO ${seqname} VALUES(NULL)");
409 if ($ondemand && DB::isError($result) &&
410 $result->getCode() == DB_ERROR_NOSUCHTABLE) {
412 $result = $this->createSequence($seq_name);
413 if (DB::isError($result)) {
420 if (DB::isError($result)) {
423 return @fbsql_insert_id($this->connection);
427 * Creates a new sequence
429 * @param string $seq_name name of the new sequence
431 * @return int DB_OK on success. A DB_Error object is returned if
435 * @see DB_common::createSequence()
438 function createSequence($seq_name)
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))');
447 // {{{ dropSequence()
452 * @param string $seq_name name of the sequence to be deleted
454 * @return int DB_OK on success. DB_Error if problems.
457 * @see DB_common::dropSequence()
460 function dropSequence($seq_name)
462 $seqname = $this->getSequenceName($seq_name);
463 return $this->query("DROP TABLE ${seqname} RESTRICT");
469 function modifyQuery($query)
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);
486 * Format input so it can be safely used in a query
488 * @param mixed $in data to be quoted
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
500 function quoteSmart($in)
502 if (is_int($in) || is_double($in)) {
504 } elseif (is_bool($in)) {
505 return $in ? 'TRUE' : 'FALSE';
506 } elseif (is_null($in)) {
509 return "'" . $this->escapeSimple($in) . "'";
514 // {{{ fbsqlRaiseError()
517 * Gather information about an error, then use that info to create a
518 * DB error object and finally return that object.
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()
526 function fbsqlRaiseError($errno = null)
528 if ($errno === null) {
529 $errno = $this->errorCode(fbsql_errno($this->connection));
531 return $this->raiseError($errno, null, null, null,
532 @fbsql_error($this->connection));
539 * Returns information about a table or a result set.
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
548 * @see DB_common::tableInfo()
550 function tableInfo($result, $mode = null) {
551 if (isset($result->result)) {
553 * Probably received a result object.
554 * Extract the result resource identifier.
556 $id = $result->result;
558 } elseif (is_string($result)) {
560 * Probably received a table name.
561 * Create a result resource identifier.
563 $id = @fbsql_list_fields($this->dsn['database'],
564 $result, $this->connection);
568 * Probably received a result resource identifier.
570 * Depricated. Here for compatibility only.
576 if (!is_resource($id)) {
577 return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA);
580 if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
581 $case_func = 'strtolower';
583 $case_func = 'strval';
586 $count = @fbsql_num_fields($id);
588 // made this IF due to performance (one if is faster than $count if's)
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);
598 $res["num_fields"]= $count;
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);
607 if ($mode & DB_TABLEINFO_ORDER) {
608 $res['order'][$res[$i]['name']] = $i;
610 if ($mode & DB_TABLEINFO_ORDERTABLE) {
611 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
616 // free the result only if we were called on a table
618 @fbsql_free_result($id);
624 // {{{ getSpecialQuery()
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
631 function getSpecialQuery($type)
635 return 'select "table_name" from information_schema.tables';