6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 if (!defined('IN_PHPBB'))
19 include_once($phpbb_root_path . 'includes/db/dbal.' . $phpEx);
22 * Firebird/Interbase Database Abstraction Layer
23 * Minimum Requirement is Firebird 2.1
26 class dbal_firebird extends dbal
28 var $last_query_text = '';
29 var $service_handle = false;
30 var $affected_rows = 0;
31 var $connect_error = '';
36 function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
38 $this->persistency = $persistency;
39 $this->user = $sqluser;
40 $this->server = $sqlserver . (($port) ? ':' . $port : '');
41 $this->dbname = str_replace('\\', '/', $database);
43 // There are three possibilities to connect to an interbase db
46 $use_database = $this->dbname;
48 else if (strpos($this->server, '//') === 0)
50 $use_database = $this->server . $this->dbname;
54 $use_database = $this->server . ':' . $this->dbname;
57 if ($this->persistency)
59 if (!function_exists('ibase_pconnect'))
61 $this->connect_error = 'ibase_pconnect function does not exist, is interbase extension installed?';
62 return $this->sql_error('');
64 $this->db_connect_id = @ibase_pconnect($use_database, $this->user, $sqlpassword, false, false, 3);
68 if (!function_exists('ibase_connect'))
70 $this->connect_error = 'ibase_connect function does not exist, is interbase extension installed?';
71 return $this->sql_error('');
73 $this->db_connect_id = @ibase_connect($use_database, $this->user, $sqlpassword, false, false, 3);
76 // Do not call ibase_service_attach if connection failed,
77 // otherwise error message from ibase_(p)connect call will be clobbered.
78 if ($this->db_connect_id && function_exists('ibase_service_attach') && $this->server)
80 $this->service_handle = @ibase_service_attach($this->server, $this->user, $sqlpassword);
84 $this->service_handle = false;
87 return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error('');
91 * Version information about used database
92 * @param bool $raw if true, only return the fetched sql_server_version
93 * @param bool $use_cache forced to false for Interbase
94 * @return string sql server version
96 function sql_server_info($raw = false, $use_cache = true)
99 * force $use_cache false. I didn't research why the caching code there is no caching code
100 * but I assume its because the IB extension provides a direct method to access it
106 if ($this->service_handle !== false && function_exists('ibase_server_info'))
108 return @ibase_server_info($this->service_handle, IBASE_SVC_SERVER_VERSION);
111 return ($raw) ? '2.1' : 'Firebird/Interbase';
118 function _sql_transaction($status = 'begin')
127 return @ibase_commit();
131 return @ibase_rollback();
141 * @param string $query Contains the SQL query which shall be executed
142 * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache
143 * @return mixed When casted to bool the returned value returns true on success and false on failure
147 function sql_query($query = '', $cache_ttl = 0)
153 // EXPLAIN only in extra debug mode
154 if (defined('DEBUG_EXTRA'))
156 $this->sql_report('start', $query);
159 $this->last_query_text = $query;
160 $this->query_result = ($cache_ttl && method_exists($cache, 'sql_load')) ? $cache->sql_load($query) : false;
161 $this->sql_add_num_queries($this->query_result);
163 if ($this->query_result === false)
166 // We overcome Firebird's 32767 char limit by binding vars
167 if (strlen($query) > 32767)
169 if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/s', $query, $regs))
171 if (strlen($regs[3]) > 32767)
173 preg_match_all('/\'(?:[^\']++|\'\')*+\'|[\d-.]+/', $regs[3], $vals, PREG_PATTERN_ORDER);
178 foreach ($inserts as $key => $value)
180 if (!empty($value) && $value[0] === "'" && strlen($value) > 32769) // check to see if this thing is greater than the max + 'x2
182 $inserts[$key] = '?';
183 $array[] = str_replace("''", "'", substr($value, 1, -1));
187 $query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')';
190 else if (preg_match('/^(UPDATE ([\\w_]++)\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|\\d+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data))
192 if (strlen($data[3]) > 32767)
196 preg_match_all('/(\\w++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[3], $temp, PREG_SET_ORDER);
200 foreach ($temp as $value)
202 if (!empty($value[2]) && $value[2][0] === "'" && strlen($value[2]) > 32769) // check to see if this thing is greater than the max + 'x2
204 $array[] = str_replace("''", "'", substr($value[2], 1, -1));
205 $cols[] = $value[1] . '=?';
209 $cols[] = $value[1] . '=' . $value[2];
213 $query = $update . implode(', ', $cols) . ' ' . $where;
219 if (!function_exists('ibase_affected_rows') && (preg_match('/^UPDATE ([\w_]++)\s+SET [\w_]++\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+)(?:,\s*[\w_]++\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+\s+(WHERE.*)?$/s', $query, $regs) || preg_match('/^DELETE FROM ([\w_]++)\s*(WHERE\s*.*)?$/s', $query, $regs)))
221 $affected_sql = 'SELECT COUNT(*) as num_rows_affected FROM ' . $regs[1];
222 if (!empty($regs[2]))
224 $affected_sql .= ' ' . $regs[2];
227 if (!($temp_q_id = @ibase_query($this->db_connect_id, $affected_sql)))
232 $temp_result = @ibase_fetch_assoc($temp_q_id);
233 @ibase_free_result($temp_q_id);
235 $this->affected_rows = ($temp_result) ? $temp_result['NUM_ROWS_AFFECTED'] : false;
240 $p_query = @ibase_prepare($this->db_connect_id, $query);
241 array_unshift($array, $p_query);
242 $this->query_result = call_user_func_array('ibase_execute', $array);
245 if ($this->query_result === false)
247 $this->sql_error($query);
250 else if (($this->query_result = @ibase_query($this->db_connect_id, $query)) === false)
252 $this->sql_error($query);
255 if (defined('DEBUG_EXTRA'))
257 $this->sql_report('stop', $query);
260 if (!$this->transaction)
262 if (function_exists('ibase_commit_ret'))
268 // way cooler than ibase_commit_ret :D
269 @ibase_query('COMMIT RETAIN;');
273 if ($cache_ttl && method_exists($cache, 'sql_save'))
275 $this->open_queries[(int) $this->query_result] = $this->query_result;
276 $cache->sql_save($query, $this->query_result, $cache_ttl);
278 else if (strpos($query, 'SELECT') === 0 && $this->query_result)
280 $this->open_queries[(int) $this->query_result] = $this->query_result;
283 else if (defined('DEBUG_EXTRA'))
285 $this->sql_report('fromcache', $query);
293 return $this->query_result;
299 function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
301 $this->query_result = false;
303 $query = 'SELECT FIRST ' . $total . ((!empty($offset)) ? ' SKIP ' . $offset : '') . substr($query, 6);
305 return $this->sql_query($query, $cache_ttl);
309 * Return number of affected rows
311 function sql_affectedrows()
314 if (function_exists('ibase_affected_rows'))
316 return ($this->db_connect_id) ? @ibase_affected_rows($this->db_connect_id) : false;
320 return $this->affected_rows;
327 function sql_fetchrow($query_id = false)
331 if ($query_id === false)
333 $query_id = $this->query_result;
336 if (isset($cache->sql_rowset[$query_id]))
338 return $cache->sql_fetchrow($query_id);
341 if ($query_id === false)
347 $cur_row = @ibase_fetch_object($query_id, IBASE_TEXT);
354 foreach (get_object_vars($cur_row) as $key => $value)
356 $row[strtolower($key)] = (is_string($value)) ? trim(str_replace(array("\\0", "\\n"), array("\0", "\n"), $value)) : $value;
359 return (sizeof($row)) ? $row : false;
363 * Seek to given row number
364 * rownum is zero-based
366 function sql_rowseek($rownum, &$query_id)
370 if ($query_id === false)
372 $query_id = $this->query_result;
375 if (isset($cache->sql_rowset[$query_id]))
377 return $cache->sql_rowseek($rownum, $query_id);
380 if ($query_id === false)
385 $this->sql_freeresult($query_id);
386 $query_id = $this->sql_query($this->last_query_text);
388 if ($query_id === false)
393 // We do not fetch the row for rownum == 0 because then the next resultset would be the second row
394 for ($i = 0; $i < $rownum; $i++)
396 if (!$this->sql_fetchrow($query_id))
406 * Get last inserted id after insert statement
408 function sql_nextid()
410 $query_id = $this->query_result;
412 if ($query_id !== false && $this->last_query_text != '')
414 if ($this->query_result && preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#i', $this->last_query_text, $tablename))
416 $sql = 'SELECT GEN_ID(' . $tablename[1] . '_gen, 0) AS new_id FROM RDB$DATABASE';
418 if (!($temp_q_id = @ibase_query($this->db_connect_id, $sql)))
423 $temp_result = @ibase_fetch_assoc($temp_q_id);
424 @ibase_free_result($temp_q_id);
426 return ($temp_result) ? $temp_result['NEW_ID'] : false;
436 function sql_freeresult($query_id = false)
440 if ($query_id === false)
442 $query_id = $this->query_result;
445 if (isset($cache->sql_rowset[$query_id]))
447 return $cache->sql_freeresult($query_id);
450 if (isset($this->open_queries[(int) $query_id]))
452 unset($this->open_queries[(int) $query_id]);
453 return @ibase_free_result($query_id);
460 * Escape string used in sql query
462 function sql_escape($msg)
464 return str_replace(array("'", "\0"), array("''", ''), $msg);
468 * Build LIKE expression
471 function _sql_like_expression($expression)
473 return $expression . " ESCAPE '\\'";
477 * Build db-specific query data
480 function _sql_custom_build($stage, $data)
485 function _sql_bit_and($column_name, $bit, $compare = '')
487 return 'BIN_AND(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : '');
490 function _sql_bit_or($column_name, $bit, $compare = '')
492 return 'BIN_OR(' . $column_name . ', ' . (1 << $bit) . ')' . (($compare) ? ' ' . $compare : '');
496 * return sql error array
499 function _sql_error()
501 // Need special handling here because ibase_errmsg returns
502 // connection errors, however if the interbase extension
503 // is not installed then ibase_errmsg does not exist and
504 // we cannot call it.
505 if (function_exists('ibase_errmsg'))
507 $msg = @ibase_errmsg();
510 $msg = $this->connect_error;
515 $msg = $this->connect_error;
519 'code' => (@function_exists('ibase_errcode') ? @ibase_errcode() : '')
524 * Close sql connection
527 function _sql_close()
529 if ($this->service_handle !== false)
531 @ibase_service_detach($this->service_handle);
534 return @ibase_close($this->db_connect_id);
538 * Build db-specific report
541 function _sql_report($mode, $query = '')
549 $endtime = explode(' ', microtime());
550 $endtime = $endtime[0] + $endtime[1];
552 $result = @ibase_query($this->db_connect_id, $query);
553 while ($void = @ibase_fetch_object($result, IBASE_TEXT))
555 // Take the time spent on parsing rows into account
557 @ibase_free_result($result);
559 $splittime = explode(' ', microtime());
560 $splittime = $splittime[0] + $splittime[1];
562 $this->sql_report('record_fromcache', $query, $endtime, $splittime);