Firebird support

git-svn-id: file:///svn/phpbb/trunk@9286 89ea8834-ac86-4346-8a33-228a782c2dd0
This commit is contained in:
Meik Sievertsen 2009-01-21 17:04:51 +00:00
parent 578beb75ef
commit ef2346098e

View file

@ -16,31 +16,78 @@ if (!defined('IN_PHPBB'))
exit;
}
include_once(PHPBB_ROOT_PATH . 'includes/db/dbal.' . PHP_EXT);
/**
* Firebird/Interbase Database Abstraction Layer
* Minimum Requirement is Firebird 2.0
* Minimum Requirement: 2.0+
* @package dbal
*/
class dbal_firebird extends dbal
class phpbb_dbal_firebird extends phpbb_dbal
{
var $last_query_text = '';
var $service_handle = false;
// can't truncate a table
var $truncate = false;
var $dbms_type = 'firebird';
/**
* @var string Database type. No distinction between versions or used extensions.
*/
public $dbms_type = 'firebird';
/**
* Connect to server
* @var array Database type map, column layout information
*/
function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
public $dbms_type_map = array(
'INT:' => 'INTEGER',
'BINT' => 'DOUBLE PRECISION',
'UINT' => 'INTEGER',
'UINT:' => 'INTEGER',
'TINT:' => 'INTEGER',
'USINT' => 'INTEGER',
'BOOL' => 'INTEGER',
'VCHAR' => 'VARCHAR(255) CHARACTER SET NONE',
'VCHAR:' => 'VARCHAR(%d) CHARACTER SET NONE',
'CHAR:' => 'CHAR(%d) CHARACTER SET NONE',
'XSTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'STEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'TEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'MTEXT' => 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
'XSTEXT_UNI'=> 'VARCHAR(100) CHARACTER SET UTF8',
'STEXT_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
'TEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
'MTEXT_UNI' => 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
'TIMESTAMP' => 'INTEGER',
'DECIMAL' => 'DOUBLE PRECISION',
'DECIMAL:' => 'DOUBLE PRECISION',
'PDECIMAL' => 'DOUBLE PRECISION',
'PDECIMAL:' => 'DOUBLE PRECISION',
'VCHAR_UNI' => 'VARCHAR(255) CHARACTER SET UTF8',
'VCHAR_UNI:'=> 'VARCHAR(%d) CHARACTER SET UTF8',
'VARBINARY' => 'CHAR(255) CHARACTER SET NONE',
);
/**
* @var string Last query executed. We need this for sql_nextid()
*/
var $last_query_text = '';
/**
* @var resource Attached service handle.
*/
var $service_handle = false;
/**
* @var array Database features
*/
public $features = array(
'multi_insert' => false,
'count_distinct' => true,
'multi_table_deletion' => true,
'truncate' => false,
);
/**
* Connect to server. See {@link phpbb_dbal::sql_connect() sql_connect()} for details.
*/
public function sql_connect($server, $user, $password, $database, $port = false, $persistency = false , $new_link = false)
{
$this->persistency = $persistency;
$this->user = $sqluser;
$this->server = $sqlserver . (($port) ? ':' . $port : '');
$this->user = $user;
$this->server = $server . (($port) ? ':' . $port : '');
$this->dbname = str_replace('\\', '/', $database);
// There are three possibilities to connect to an interbase db
@ -57,110 +104,155 @@ class dbal_firebird extends dbal
$use_database = $this->server . ':' . $this->dbname;
}
$this->db_connect_id = ($this->persistency) ? @ibase_pconnect($use_database, $this->user, $sqlpassword, false, false, 3) : @ibase_connect($use_database, $this->user, $sqlpassword, false, false, 3);
$this->db_connect_id = ($this->persistency) ? @ibase_pconnect($use_database, $this->user, $password, false, false, 3) : @ibase_connect($use_database, $this->user, $password, false, false, 3);
$this->service_handle = (strtolower($this->user) == 'sysdba' && $this->server) ? @ibase_service_attach($this->server, $this->user, $sqlpassword) : false;
if (!$this->db_connect_id)
{
return $this->sql_error('');
}
return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
$this->service_handle = ($this->server) ? @ibase_service_attach($this->server, $this->user, $password) : false;
return $this->db_connect_id;
}
/**
* Version information about used database
* @param bool $raw if true, only return the fetched sql_server_version
* @return string sql server version
* Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details.
*/
function sql_server_info($raw = false)
public function sql_server_info($raw = false)
{
if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#firebird_version')) === false)
{
$version = false;
if ($this->service_handle !== false)
{
$val = @ibase_server_info($this->service_handle, IBASE_SVC_SERVER_VERSION);
preg_match('#V([\d.]+)#', $val, $version);
$version = (!empty($version[1])) ? $version[1] : false;
}
$this->sql_server_version = (!$version) ? '2.0' : $version;
if (phpbb::registered('acm'))
{
phpbb::$acm->put('#firebird_version', $this->sql_server_version);
}
}
return ($raw) ? $this->sql_server_version : 'Firebird/Interbase ' . $this->sql_server_version;
}
/**
* DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details.
*/
protected function _sql_query($query)
{
$this->last_query_text = $query;
$array = array();
// We overcome Firebird's 32767 char limit by binding vars
if (strlen($query) > 32767)
{
if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/s', $query, $regs))
{
if (strlen($regs[3]) > 32767)
{
preg_match_all('/\'(?:[^\']++|\'\')*+\'|[\d-.]+/', $regs[3], $vals, PREG_PATTERN_ORDER);
$inserts = $vals[0];
unset($vals);
foreach ($inserts as $key => $value)
{
// check to see if this thing is greater than the max + 'x2
if (!empty($value) && $value[0] === "'" && strlen($value) > 32769)
{
$inserts[$key] = '?';
$array[] = str_replace("''", "'", substr($value, 1, -1));
}
}
$query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')';
}
}
else if (preg_match('/^(UPDATE ([\\w_]++)\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|\\d+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data))
{
if (strlen($data[3]) > 32767)
{
$update = $data[1];
$where = $data[4];
preg_match_all('/(\\w++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[3], $temp, PREG_SET_ORDER);
unset($data);
$cols = array();
foreach ($temp as $value)
{
// check to see if this thing is greater than the max + 'x2
if (!empty($value[2]) && $value[2][0] === "'" && strlen($value[2]) > 32769)
{
$array[] = str_replace("''", "'", substr($value[2], 1, -1));
$cols[] = $value[1] . '=?';
}
else
{
$cols[] = $value[1] . '=' . $value[2];
}
}
$query = $update . implode(', ', $cols) . ' ' . $where;
unset($cols);
}
}
}
if (sizeof($array))
{
$p_query = @ibase_prepare($this->db_connect_id, $query);
array_unshift($array, $p_query);
$result = call_user_func_array('ibase_execute', $array);
unset($array);
}
else
{
$result = @ibase_query($this->db_connect_id, $query);
if ($result && !$this->transaction)
{
@ibase_commit_ret();
}
}
return $result;
}
/**
* Build LIMIT query and run it. See {@link phpbb_dbal::_sql_query_limit() _sql_query_limit()} for details.
*/
protected function _sql_query_limit($query, $total, $offset, $cache_ttl)
{
$query = 'SELECT FIRST ' . $total . ((!empty($offset)) ? ' SKIP ' . $offset : '') . substr($query, 6);
return $this->sql_query($query, $cache_ttl);
}
/**
* Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details.
*/
protected function _sql_close()
{
if ($this->service_handle !== false)
{
return @ibase_server_info($this->service_handle, IBASE_SVC_SERVER_VERSION);
@ibase_service_detach($this->service_handle);
}
/* // check the version of FB, use some hackery if we can't get access to the server info
if ($db->service_handle !== false && strtolower($dbuser) == 'sysdba')
{
$val = @ibase_server_info($db->service_handle, IBASE_SVC_SERVER_VERSION);
preg_match('#V([\d.]+)#', $val, $match);
if ($match[1] < 2)
{
$error[] = $lang['INST_ERR_DB_NO_FIREBIRD'];
}
$db_info = @ibase_db_info($db->service_handle, $dbname, IBASE_STS_HDR_PAGES);
preg_match('/^\\s*Page size\\s*(\\d+)/m', $db_info, $regs);
$page_size = intval($regs[1]);
if ($page_size < 8192)
{
$error[] = $lang['INST_ERR_DB_NO_FIREBIRD_PS'];
}
}
else
{
$sql = "SELECT *
FROM RDB$FUNCTIONS
WHERE RDB$SYSTEM_FLAG IS NULL
AND RDB$FUNCTION_NAME = 'CHAR_LENGTH'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
// if its a UDF, its too old
if ($row)
{
$error[] = $lang['INST_ERR_DB_NO_FIREBIRD'];
}
else
{
$sql = "SELECT FIRST 0 char_length('')
FROM RDB\$DATABASE";
$result = $db->sql_query($sql);
if (!$result) // This can only fail if char_length is not defined
{
$error[] = $lang['INST_ERR_DB_NO_FIREBIRD'];
}
$db->sql_freeresult($result);
}
// Setup the stuff for our random table
$char_array = array_merge(range('A', 'Z'), range('0', '9'));
$char_len = mt_rand(7, 9);
$char_array_len = sizeof($char_array) - 1;
$final = '';
for ($i = 0; $i < $char_len; $i++)
{
$final .= $char_array[mt_rand(0, $char_array_len)];
}
// Create some random table
$sql = 'CREATE TABLE ' . $final . " (
FIELD1 VARCHAR(255) CHARACTER SET UTF8 DEFAULT '' NOT NULL COLLATE UNICODE,
FIELD2 INTEGER DEFAULT 0 NOT NULL);";
$db->sql_query($sql);
// Create an index that should fail if the page size is less than 8192
$sql = 'CREATE INDEX ' . $final . ' ON ' . $final . '(FIELD1, FIELD2);';
$db->sql_query($sql);
if (ibase_errmsg() !== false)
{
$error[] = $lang['INST_ERR_DB_NO_FIREBIRD_PS'];
}
// Kill the old table
$db->sql_query('DROP TABLE ' . $final . ';');
unset($final);
}
*/
return ($raw) ? '2.0' : 'Firebird/Interbase';
return @ibase_close($this->db_connect_id);
}
/**
* SQL Transaction
* @access private
* SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details.
*/
function _sql_transaction($status = 'begin')
protected function _sql_transaction($status)
{
switch ($status)
{
@ -181,179 +273,46 @@ class dbal_firebird extends dbal
}
/**
* Base query method
*
* @param string $query Contains the SQL query which shall be executed
* @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
* @return mixed When casted to bool the returned value returns true on success and false on failure
*
* @access public
* Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details.
*/
function sql_query($query = '', $cache_ttl = 0)
{
if ($query != '')
{
global $cache;
// EXPLAIN only in extra debug mode
if (defined('DEBUG_EXTRA'))
{
$this->sql_report('start', $query);
}
$this->last_query_text = $query;
$this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
$this->sql_add_num_queries($this->query_result);
if ($this->query_result === false)
{
$array = array();
// We overcome Firebird's 32767 char limit by binding vars
if (strlen($query) > 32767)
{
if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/s', $query, $regs))
{
if (strlen($regs[3]) > 32767)
{
preg_match_all('/\'(?:[^\']++|\'\')*+\'|[\d-.]+/', $regs[3], $vals, PREG_PATTERN_ORDER);
$inserts = $vals[0];
unset($vals);
foreach ($inserts as $key => $value)
{
if (!empty($value) && $value[0] === "'" && strlen($value) > 32769) // check to see if this thing is greater than the max + 'x2
{
$inserts[$key] = '?';
$array[] = str_replace("''", "'", substr($value, 1, -1));
}
}
$query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')';
}
}
else if (preg_match('/^(UPDATE ([\\w_]++)\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|\\d+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data))
{
if (strlen($data[3]) > 32767)
{
$update = $data[1];
$where = $data[4];
preg_match_all('/(\\w++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[3], $temp, PREG_SET_ORDER);
unset($data);
$cols = array();
foreach ($temp as $value)
{
if (!empty($value[2]) && $value[2][0] === "'" && strlen($value[2]) > 32769) // check to see if this thing is greater than the max + 'x2
{
$array[] = str_replace("''", "'", substr($value[2], 1, -1));
$cols[] = $value[1] . '=?';
}
else
{
$cols[] = $value[1] . '=' . $value[2];
}
}
$query = $update . implode(', ', $cols) . ' ' . $where;
unset($cols);
}
}
}
if (sizeof($array))
{
$p_query = @ibase_prepare($this->db_connect_id, $query);
array_unshift($array, $p_query);
$this->query_result = call_user_func_array('ibase_execute', $array);
unset($array);
if ($this->query_result === false)
{
$this->sql_error($query);
}
}
else if (($this->query_result = @ibase_query($this->db_connect_id, $query)) === false)
{
$this->sql_error($query);
}
if (defined('DEBUG_EXTRA'))
{
$this->sql_report('stop', $query);
}
if (!$this->transaction)
{
@ibase_commit_ret();
}
if ($cache_ttl && method_exists($cache, 'sql_save'))
{
$this->open_queries[(int) $this->query_result] = $this->query_result;
$cache->sql_save($query, $this->query_result, $cache_ttl);
}
else if (strpos($query, 'SELECT') === 0 && $this->query_result)
{
$this->open_queries[(int) $this->query_result] = $this->query_result;
}
}
else if (defined('DEBUG_EXTRA'))
{
$this->sql_report('fromcache', $query);
}
}
else
{
return false;
}
return $this->query_result;
}
/**
* Build LIMIT query
*/
function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
{
$this->query_result = false;
$query = 'SELECT FIRST ' . $total . ((!empty($offset)) ? ' SKIP ' . $offset : '') . substr($query, 6);
return $this->sql_query($query, $cache_ttl);
}
/**
* Return number of affected rows
*/
function sql_affectedrows()
public function sql_affectedrows()
{
return ($this->db_connect_id) ? @ibase_affected_rows($this->db_connect_id) : false;
}
/**
* Fetch current row
* Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details.
*/
function sql_fetchrow($query_id = false)
public function sql_nextid()
{
global $cache;
if ($query_id === false)
{
$query_id = $this->query_result;
}
if (isset($cache->sql_rowset[$query_id]))
{
return $cache->sql_fetchrow($query_id);
}
if ($query_id === false)
if (!$this->query_result || !$this->last_query_text)
{
return false;
}
$row = array();
if (preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#i', $this->last_query_text, $tablename))
{
$sql = 'SELECT GEN_ID(' . $tablename[1] . '_gen, 0) AS new_id FROM RDB$DATABASE';
if (!($temp_q_id = @ibase_query($this->db_connect_id, $sql)))
{
return false;
}
$temp_result = @ibase_fetch_assoc($temp_q_id);
@ibase_free_result($temp_q_id);
return ($temp_result) ? $temp_result['NEW_ID'] : false;
}
return false;
}
/**
* Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details.
*/
protected function _sql_fetchrow($query_id)
{
$cur_row = @ibase_fetch_object($query_id, IBASE_TEXT);
if (!$cur_row)
@ -370,71 +329,33 @@ class dbal_firebird extends dbal
}
/**
* Get last inserted id after insert statement
* Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details.
*/
function sql_nextid()
protected function _sql_freeresult($query_id)
{
$query_id = $this->query_result;
if ($query_id !== false && $this->last_query_text != '')
{
if ($this->query_result && preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#i', $this->last_query_text, $tablename))
{
$sql = 'SELECT GEN_ID(' . $tablename[1] . '_gen, 0) AS new_id FROM RDB$DATABASE';
if (!($temp_q_id = @ibase_query($this->db_connect_id, $sql)))
{
return false;
}
$temp_result = @ibase_fetch_assoc($temp_q_id);
@ibase_free_result($temp_q_id);
return ($temp_result) ? $temp_result['NEW_ID'] : false;
}
}
return false;
return @ibase_free_result($query_id);
}
/**
* Free sql result
* Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details.
*/
function sql_freeresult($query_id = false)
protected function _sql_like_expression($expression)
{
global $cache;
if ($query_id === false)
{
$query_id = $this->query_result;
}
if (isset($cache->sql_rowset[$query_id]))
{
return $cache->sql_freeresult($query_id);
}
if (isset($this->open_queries[(int) $query_id]))
{
unset($this->open_queries[(int) $query_id]);
return @ibase_free_result($query_id);
}
return false;
return $expression . " ESCAPE '\\'";
}
/**
* Escape string used in sql query
* Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details.
*/
function sql_escape($msg)
public function sql_escape($msg)
{
return str_replace(array("'", "\0"), array("''", ''), $msg);
}
/**
* Expose a DBMS specific function
* Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details.
*/
function sql_function($type, $col)
public function sql_function($type, $col)
{
switch ($type)
{
@ -445,7 +366,9 @@ class dbal_firebird extends dbal
}
}
function sql_handle_data($type, $table, $data, $where = '')
/**
* Handle data by using prepared statements. See {@link phpbb_dbal::sql_handle_data() sql_handle_data()} for details.
public function sql_handle_data($type, $table, $data, $where = '')
{
if ($type == 'INSERT')
{
@ -475,30 +398,20 @@ class dbal_firebird extends dbal
call_user_func_array('ibase_execute', $data);
}
*/
/**
* Build LIKE expression
* @access private
* Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details.
*/
function _sql_like_expression($expression)
{
return $expression . " ESCAPE '\\'";
}
/**
* Build db-specific query data
* @access private
*/
function _sql_custom_build($stage, $data)
protected function _sql_custom_build($stage, $data)
{
return $data;
}
/**
* return sql error array
* @access private
* return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details.
*/
function _sql_error()
protected function _sql_error()
{
return array(
'message' => @ibase_errmsg(),
@ -507,24 +420,9 @@ class dbal_firebird extends dbal
}
/**
* Close sql connection
* @access private
* Run DB-specific code to build SQL Report to explain queries, show statistics and runtime information. See {@link phpbb_dbal::_sql_report() _sql_report()} for details.
*/
function _sql_close()
{
if ($this->service_handle !== false)
{
@ibase_service_detach($this->service_handle);
}
return @ibase_close($this->db_connect_id);
}
/**
* Build db-specific report
* @access private
*/
function _sql_report($mode, $query = '')
protected function _sql_report($mode, $query = '')
{
switch ($mode)
{