diff options
author | Meik Sievertsen <acydburn@phpbb.com> | 2009-10-04 18:13:59 +0000 |
---|---|---|
committer | Meik Sievertsen <acydburn@phpbb.com> | 2009-10-04 18:13:59 +0000 |
commit | bf8ac19eaa8d74f9dfd6d597190f5664e7339382 (patch) | |
tree | c3ad876736748e36cb9176a0248cc43badfc1d9a /phpBB/includes/db | |
parent | 3215bbf88864139dc8c7e9ac5773b1ea8a7e96c1 (diff) | |
download | forums-bf8ac19eaa8d74f9dfd6d597190f5664e7339382.tar forums-bf8ac19eaa8d74f9dfd6d597190f5664e7339382.tar.gz forums-bf8ac19eaa8d74f9dfd6d597190f5664e7339382.tar.bz2 forums-bf8ac19eaa8d74f9dfd6d597190f5664e7339382.tar.xz forums-bf8ac19eaa8d74f9dfd6d597190f5664e7339382.zip |
Move trunk/phpBB to old_trunk/phpBB
git-svn-id: file:///svn/phpbb/trunk@10210 89ea8834-ac86-4346-8a33-228a782c2dd0
Diffstat (limited to 'phpBB/includes/db')
-rw-r--r-- | phpBB/includes/db/db2.php | 455 | ||||
-rw-r--r-- | phpBB/includes/db/db_tools.php | 1707 | ||||
-rw-r--r-- | phpBB/includes/db/dbal.php | 1553 | ||||
-rw-r--r-- | phpBB/includes/db/firebird.php | 453 | ||||
-rw-r--r-- | phpBB/includes/db/mssql.php | 382 | ||||
-rw-r--r-- | phpBB/includes/db/mssql_2005.php | 350 | ||||
-rw-r--r-- | phpBB/includes/db/mssql_odbc.php | 380 | ||||
-rw-r--r-- | phpBB/includes/db/mysql.php | 447 | ||||
-rw-r--r-- | phpBB/includes/db/mysqli.php | 472 | ||||
-rw-r--r-- | phpBB/includes/db/oracle.php | 664 | ||||
-rw-r--r-- | phpBB/includes/db/postgres.php | 409 | ||||
-rw-r--r-- | phpBB/includes/db/sqlite.php | 307 |
12 files changed, 0 insertions, 7579 deletions
diff --git a/phpBB/includes/db/db2.php b/phpBB/includes/db/db2.php deleted file mode 100644 index 87210d6534..0000000000 --- a/phpBB/includes/db/db2.php +++ /dev/null @@ -1,455 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2009 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* MSSQL Database Abstraction Layer -* Minimum Requirement: DB2 8.2.2+ -* Minimum extension version: PECL ibm_db2 1.6.0+ -* @package dbal -*/ -class phpbb_dbal_db2 extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'db2'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'integer', - 'BINT' => 'float', - 'UINT' => 'integer', - 'UINT:' => 'integer', - 'TINT:' => 'smallint', - 'USINT' => 'smallint', - 'BOOL' => 'smallint', - 'VCHAR' => 'varchar(255)', - 'VCHAR:' => 'varchar(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'clob(65K)', - 'STEXT' => 'varchar(3000)', - 'TEXT' => 'clob(65K)', - 'MTEXT' => 'clob(16M)', - 'XSTEXT_UNI'=> 'varchar(100)', - 'STEXT_UNI' => 'varchar(255)', - 'TEXT_UNI' => 'clob(65K)', - 'MTEXT_UNI' => 'clob(16M)', - 'TIMESTAMP' => 'integer', - 'DECIMAL' => 'float', - 'VCHAR_UNI' => 'varchar(255)', - 'VCHAR_UNI:'=> 'varchar(%d)', - 'VARBINARY' => 'varchar(255)', - ); - - /** - * @var array Database features - */ - public $features = array( - 'multi_insert' => true, - '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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = $database; - $this->port = $port; - - $this->db_connect_id = ($this->persistency) ? @db2_pconnect($this->dbname, $this->user, $password, array('autocommit' => DB2_AUTOCOMMIT_ON, 'DB2_ATTR_CASE' => DB2_CASE_LOWER)) : @db2_connect($this->dbname, $this->user, $password, array('autocommit' => DB2_AUTOCOMMIT_ON, 'DB2_ATTR_CASE' => DB2_CASE_LOWER)); - - return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#db2_version')) === false) - { - $info = @db2_server_info($this->db_connect_id); - - $this->sql_server_info = is_object($info) ? $info->DBMS_VER : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#db2_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'IBM DB2 ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - $array = array(); - - // Cope with queries larger than 32K - if (strlen($query) > 32740) - { - if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/s', $query, $regs)) - { - if (strlen($regs[3]) > 32740) - { - 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) > 32742) - { - $inserts[$key] = '?'; - $array[] = str_replace("''", "'", substr($value, 1, -1)); - } - } - - $query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')'; - } - } - else if (preg_match_all('/^(UPDATE ([\\w_]++)\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data, PREG_SET_ORDER)) - { - if (strlen($data[0][3]) > 32740) - { - $update = $data[0][1]; - $where = $data[0][4]; - preg_match_all('/(\\w++) = (\'(?:[^\']++|\'\')*+\'|\\d++)/', $data[0][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]) > 32742) - { - $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)) - { - $result = @db2_prepare($this->db_connect_id, $query); - - if (!$result) - { - return false; - } - - if (!@db2_execute($result, $array)) - { - return false; - } - } - else - { - $result = @db2_exec($this->db_connect_id, $query); - } - - 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) - { - if ($total && $offset == 0) - { - return $this->sql_query($query . ' fetch first ' . $total . ' rows only', $cache_ttl); - } - - // Seek by $offset rows - if ($offset) - { - $limit_sql = 'SELECT a2.* - FROM ( - SELECT ROW_NUMBER() OVER() AS rownum, a1.* - FROM ( - ' . $query . ' - ) a1 - ) a2 - WHERE a2.rownum BETWEEN ' . ($offset + 1) . ' AND ' . ($offset + $total); - - return $this->sql_query($limit_sql, $cache_ttl); - } - - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @db2_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @db2_autocommit($this->db_connect_id, DB2_AUTOCOMMIT_OFF); - break; - - case 'commit': - $result = @db2_commit($this->db_connect_id); - @db2_autocommit($this->db_connect_id, DB2_AUTOCOMMIT_ON); - return $result; - break; - - case 'rollback': - $result = @db2_rollback($this->db_connect_id); - @db2_autocommit($this->db_connect_id, DB2_AUTOCOMMIT_ON); - return $result; - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @db2_num_rows($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - if (function_exists('db2_last_insert_id')) - { - return @db2_last_insert_id($this->db_connect_id); - } - - $result_id = @db2_exec($this->db_connect_id, 'VALUES IDENTITY_VAL_LOCAL()'); - - if ($result_id) - { - if ($row = @db2_fetch_assoc($result_id)) - { - @db2_free_result($result_id); - return (int) $row[1]; - } - @db2_free_result($result_id); - } - - return false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - return @db2_fetch_assoc($query_id); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @db2_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return @db2_escape_string($msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'LENGTH(' . $col . ')'; - break; - } - } - - /** - * 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') - { - $stmt = db2_prepare($this->db_connect_id, "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES (" . substr(str_repeat('?, ', sizeof($data)) ,0, -1) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key) - { - $set[] = "$key = ?"; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= $where; - } - - $stmt = db2_prepare($this->db_connect_id, $query); - } - - // get the stmt onto the top of the function arguments - array_unshift($data, $stmt); - - call_user_func_array('db2_execute', $data); - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - $message = @db2_stmt_errormsg(); - $code = @db2_stmt_error(); - - if (!$message && !$code) - { - $message = @db2_conn_errormsg(); - $code = @db2_conn_error(); - } - - $error = array( - 'message' => $message, - 'code' => $code, - ); - - return $error; - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - - $html_table = false; - @db2_exec($this->db_connect_id, 'DELETE FROM EXPLAIN_INSTANCE'); - @db2_exec($this->db_connect_id, 'EXPLAIN PLAN FOR ' . $query); - - // Get the data from the plan - $sql = "SELECT O.Operator_ID, S2.Target_ID, O.Operator_Type, S.Object_Name, CAST(O.Total_Cost AS INTEGER) Cost - FROM EXPLAIN_OPERATOR O - LEFT OUTER JOIN EXPLAIN_STREAM S2 ON O.Operator_ID = S2.Source_ID - LEFT OUTER JOIN EXPLAIN_STREAM S ON O.Operator_ID = S.Target_ID AND O.Explain_Time = S.Explain_Time AND S.Object_Name IS NOT NULL - ORDER BY O.Explain_Time ASC, Operator_ID ASC"; - $query_id = @db2_exec($this->db_connect_id, $sql); - - if ($query_id) - { - while ($row = @db2_fetch_assoc($query_id)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - - @db2_free_result($query_id); - } - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @db2_exec($this->db_connect_id, $query); - while ($void = @db2_fetch_assoc($result, IBASE_TEXT)) - { - // Take the time spent on parsing rows into account - } - @db2_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/db_tools.php b/phpBB/includes/db/db_tools.php deleted file mode 100644 index 32ee807952..0000000000 --- a/phpBB/includes/db/db_tools.php +++ /dev/null @@ -1,1707 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2007 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* Database Tools for handling cross-db actions such as altering columns, etc. -* -* @package dbal -*/ -class phpbb_db_tools -{ - /** - * @var object DB object - */ - public $db = NULL; - - /** - * A list of types being unsigned for better reference in some db's - * @var array - */ - public $unsigned_types = array('UINT', 'UINT:', 'USINT', 'BOOL', 'TIMESTAMP'); - - /** - * A list of supported DBMS. We change this class to support more DBMS, the DBMS itself only need to follow some rules. - * @var array - */ - public $supported_dbms = array('mysql', 'mssql', 'sqlite', 'oracle', 'firebird', 'db2', 'postgres'); - - /** - * This is set to true if user only wants to return the 'to-be-executed' SQL statement(s) (as an array). - * This mode has no effect on some methods (inserting of data for example). This is expressed within the methods command. - */ - public $return_statements = false; - - /** - * Constructor. Set DB Object and set {@link $return_statements return_statements}. - * - * @param phpbb_dbal $db DBAL object - * @param bool $return_statements True if only statements should be returned and no SQL being executed - */ - public function __construct(phpbb_dbal $db, $return_statements = false) - { - $this->db = $db; - $this->return_statements = $return_statements; - - if (!in_array($this->db->dbms_type, $this->supported_dbms)) - { - trigger_error('DBMS Type ' . $this->db->dbms_type . ' not supported by DB Tools.', E_USER_ERROR); - } - } - - /** - * Create SQL Table - * - * @param string $table_name The table name to create - * @param array $table_data Array containing table data. For a sample layout see {@example } - * @return array Statements if $return_statements is true. - */ - public function sql_create_table($table_name, $table_data) - { - // holds the DDL for a column - $columns = $statements = array(); - - // Begin transaction - $statements[] = 'begin'; - - // Determine if we have created a PRIMARY KEY in the earliest - $primary_key_gen = false; - - // Determine if the table must be created with TEXTIMAGE - $create_textimage = false; - - // Determine if the table requires a sequence - $create_sequence = false; - - // Begin table sql statement - switch ($this->sql_layer) - { - case 'mssql': - $table_sql = 'CREATE TABLE [' . $table_name . '] (' . "\n"; - break; - - default: - $table_sql = 'CREATE TABLE ' . $table_name . ' (' . "\n"; - break; - } - - // Iterate through the columns to create a table - foreach ($table_data['COLUMNS'] as $column_name => $column_data) - { - // here lies an array, filled with information compiled on the column's data - $prepared_column = $this->sql_prepare_column_data($table_name, $column_name, $column_data); - - // here we add the definition of the new column to the list of columns - switch ($this->sql_layer) - { - case 'mssql': - $columns[] = "\t [{$column_name}] " . $prepared_column['column_type_sql_default']; - break; - - default: - $columns[] = "\t {$column_name} " . $prepared_column['column_type_sql']; - break; - } - - // see if we have found a primary key set due to a column definition if we have found it, we can stop looking - if (!$primary_key_gen) - { - $primary_key_gen = isset($prepared_column['primary_key_set']) && $prepared_column['primary_key_set']; - } - - // create textimage DDL based off of the existance of certain column types - if (!$create_textimage) - { - $create_textimage = isset($prepared_column['textimage']) && $prepared_column['textimage']; - } - - // create sequence DDL based off of the existance of auto incrementing columns - if (!$create_sequence && isset($prepared_column['auto_increment']) && $prepared_column['auto_increment']) - { - $create_sequence = $column_name; - } - } - - // this makes up all the columns in the create table statement - $table_sql .= implode(",\n", $columns); - - // Close the table for two DBMS and add to the statements - switch ($this->db->dbms_type) - { - case 'firebird': - $table_sql .= "\n);"; - $statements[] = $table_sql; - break; - - case 'mssql': - $table_sql .= "\n) ON [PRIMARY]" . (($create_textimage) ? ' TEXTIMAGE_ON [PRIMARY]' : ''); - $statements[] = $table_sql; - break; - } - - // we have yet to create a primary key for this table, - // this means that we can add the one we really wanted instead - if (!$primary_key_gen) - { - // Write primary key - if (isset($table_data['PRIMARY_KEY'])) - { - if (!is_array($table_data['PRIMARY_KEY'])) - { - $table_data['PRIMARY_KEY'] = array($table_data['PRIMARY_KEY']); - } - - switch ($this->db->dbms_type) - { - case 'mysql': - case 'postgres': - case 'db2': - case 'sqlite': - $table_sql .= ",\n\t PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')'; - break; - - case 'firebird': - case 'mssql': - $primary_key_stmts = $this->sql_create_primary_key($table_name, $table_data['PRIMARY_KEY']); - foreach ($primary_key_stmts as $pk_stmt) - { - $statements[] = $pk_stmt; - } - break; - - case 'oracle': - $table_sql .= ",\n\t CONSTRAINT pk_{$table_name} PRIMARY KEY (" . implode(', ', $table_data['PRIMARY_KEY']) . ')'; - break; - } - } - } - - // close the table - switch ($this->db->dbms_type) - { - case 'mysql': - // make sure the table is in UTF-8 mode - $table_sql .= "\n) CHARACTER SET `utf8` COLLATE `utf8_bin`;"; - $statements[] = $table_sql; - break; - - case 'postgres': - // do we need to add a sequence for auto incrementing columns? - if ($create_sequence) - { - $statements[] = "CREATE SEQUENCE {$table_name}_seq;"; - } - - $table_sql .= "\n);"; - $statements[] = $table_sql; - break; - - case 'db2': - case 'sqlite': - $table_sql .= "\n);"; - $statements[] = $table_sql; - break; - - case 'oracle': - $table_sql .= "\n);"; - $statements[] = $table_sql; - - // do we need to add a sequence and a tigger for auto incrementing columns? - if ($create_sequence) - { - // create the actual sequence - $statements[] = "CREATE SEQUENCE {$table_name}_seq"; - - // the trigger is the mechanism by which we increment the counter - $trigger = "CREATE OR REPLACE TRIGGER t_{$table_name}\n"; - $trigger .= "BEFORE INSERT ON {$table_name}\n"; - $trigger .= "FOR EACH ROW WHEN (\n"; - $trigger .= "\tnew.{$create_sequence} IS NULL OR new.{$create_sequence} = 0\n"; - $trigger .= ")\n"; - $trigger .= "BEGIN\n"; - $trigger .= "\tSELECT {$table_name}_seq.nextval\n"; - $trigger .= "\tINTO :new.{$create_sequence}\n"; - $trigger .= "\tFROM dual\n"; - $trigger .= "END;"; - - $statements[] = $trigger; - } - break; - - case 'firebird': - if ($create_sequence) - { - $statements[] = "CREATE SEQUENCE {$table_name}_seq;"; - } - break; - } - - // Write Keys - if (isset($table_data['KEYS'])) - { - foreach ($table_data['KEYS'] as $key_name => $key_data) - { - if (!is_array($key_data[1])) - { - $key_data[1] = array($key_data[1]); - } - - $old_return_statements = $this->return_statements; - $this->return_statements = true; - - $key_stmts = ($key_data[0] == 'UNIQUE') ? $this->sql_create_unique_index($table_name, $key_name, $key_data[1]) : $this->sql_create_index($table_name, $key_name, $key_data[1]); - - foreach ($key_stmts as $key_stmt) - { - $statements[] = $key_stmt; - } - - $this->return_statements = $old_return_statements; - } - } - - // Commit Transaction - $statements[] = 'commit'; - - return $this->_sql_run_sql($statements); - } - - /** - * Handle passed database update array. Update table schema. - * - * Key being one of the following - * <pre> - * change_columns - Column changes (only type, not name) - * add_columns - Add columns to a table - * drop_keys - Dropping keys - * drop_columns - Removing/Dropping columns - * add_primary_keys - adding primary keys - * add_unique_index - adding an unique index - * add_index - adding an index - * </pre> - * - * For a complete definition of the layout please see {@example } - * - * @param array $schema_changes The schema array - */ - public function sql_schema_changes($schema_changes) - { - if (empty($schema_changes)) - { - return; - } - - $statements = array(); - - // Change columns? - if (!empty($schema_changes['change_columns'])) - { - foreach ($schema_changes['change_columns'] as $table => $columns) - { - foreach ($columns as $column_name => $column_data) - { - // If the column exists we change it, else we add it ;) - if ($this->sql_column_exists($table, $column_name)) - { - $result = $this->sql_column_change($table, $column_name, $column_data); - } - else - { - $result = $this->sql_column_add($table, $column_name, $column_data); - } - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - - // Add columns? - if (!empty($schema_changes['add_columns'])) - { - foreach ($schema_changes['add_columns'] as $table => $columns) - { - foreach ($columns as $column_name => $column_data) - { - // Only add the column if it does not exist yet, else change it (to be consistent) - if ($this->sql_column_exists($table, $column_name)) - { - $result = $this->sql_column_change($table, $column_name, $column_data); - } - else - { - $result = $this->sql_column_add($table, $column_name, $column_data); - } - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - - // Remove keys? - if (!empty($schema_changes['drop_keys'])) - { - foreach ($schema_changes['drop_keys'] as $table => $indexes) - { - foreach ($indexes as $index_name) - { - $result = $this->sql_index_drop($table, $index_name); - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - - // Drop columns? - if (!empty($schema_changes['drop_columns'])) - { - foreach ($schema_changes['drop_columns'] as $table => $columns) - { - foreach ($columns as $column) - { - // Only remove the column if it exists... - if ($this->sql_column_exists($table, $column)) - { - $result = $this->sql_column_remove($table, $column); - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - } - - // Add primary keys? - if (!empty($schema_changes['add_primary_keys'])) - { - foreach ($schema_changes['add_primary_keys'] as $table => $columns) - { - $result = $this->sql_create_primary_key($table, $columns); - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - - // Add unqiue indexes? - if (!empty($schema_changes['add_unique_index'])) - { - foreach ($schema_changes['add_unique_index'] as $table => $index_array) - { - foreach ($index_array as $index_name => $column) - { - $result = $this->sql_create_unique_index($table, $index_name, $column); - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - - // Add indexes? - if (!empty($schema_changes['add_index'])) - { - foreach ($schema_changes['add_index'] as $table => $index_array) - { - foreach ($index_array as $index_name => $column) - { - $result = $this->sql_create_index($table, $index_name, $column); - - if ($this->return_statements) - { - $statements = array_merge($statements, $result); - } - } - } - } - - if ($this->return_statements) - { - return $statements; - } - } - - /** - * Insert SQL data into tables (INSERT). This function DOES NOT SUPPORT $return_statements. SQL queries are executed as is. - * For a complete definition of the layout see {@example } - * - * @param array $schema_data The schema data array - * @param array &$data A replacement array for replacing template variables within the schema - */ - public function sql_insert_data($schema_data, &$data) - { - // Go through the columns and define our type and column name for each column - $keys = $types = array(); - - foreach ($schema_data['columns'] as $column) - { - if (strpos($column, ':') === false) - { - $types[] = false; - $keys[] = $column; - continue; - } - - list($type, $column) = explode(':', $column, 2); - $types[] = $type; - $keys[] = $column; - } - - $size = sizeof($keys); - - // Go through the data array... - foreach ($schema_data['data'] as $key => $row) - { - // Get special values - foreach ($row as $_key => $value) - { - // Special case... - $row[$_key] = $this->_sql_get_special_row($value, $data); - - if ($types[$_key] === false) - { - settype($row[$_key], gettype($row[$_key])); - } - else - { - settype($row[$_key], $types[$_key]); - } - } - - // Build SQL array for INSERT - $sql = 'INSERT INTO ' . $schema_data['table'] . ' ' . $this->db->sql_build_array('INSERT', array_combine($keys, $row)); - $this->db->sql_query($sql); - - if (!empty($schema_data['store_auto_increment'])) - { - $this->stored_increments[$schema_data['store_auto_increment']][$key] = $this->db->sql_nextid(); - } - } - } - - /** - * Update SQL data in tables (UPDATE). This function DOES NOT SUPPORT $return_statements. SQL queries are executed as is. - * For a complete definition of the layout see {@example } - * - * @param array $schema_data The schema data array - * @param array &$data A replacement array for replacing template variables within the schema - */ - public function sql_update_data($schema_data, &$data) - { - // Go through the data array... - $row = $schema_data['data']; - - // Get special values - foreach ($row as $key => $value) - { - $row[$key] = $this->_sql_get_special_row($value, $data); - } - - // Build SQL array for UPDATE - $sql_ary = array_combine(array_values($schema_data['columns']), $row); - - $sql = 'UPDATE ' . $schema_data['table'] . ' SET ' . $this->db->sql_build_array('UPDATE', $sql_ary); - - // Is WHERE statement there? - if (!empty($schema_data['where'])) - { - $where_statements = array(); - foreach ($schema_data['where'] as $_key => $array) - { - foreach ($array as $key => $value) - { - $value = $this->_sql_get_special_row($value, $data); - - if (is_string($value)) - { - $where_statements[] = $key . " = '" . $this->db->sql_escape($value) . "'"; - } - else - { - $where_statements[] = $key . ' = ' . $value; - } - } - } - - if (sizeof($where_statements)) - { - $sql .= ' WHERE ' . implode(' AND ', $where_statements); - } - } - - $this->db->sql_query($sql); - } - - /** - * Check if a specified column exist - * - * @param string $table Table to check the column at - * @param string $column_name The column to check - * - * @return bool True if column exists, else false - */ - public function sql_column_exists($table, $column_name) - { - switch ($this->db->dbms_type) - { - case 'mysql': - - $sql = "SHOW COLUMNS FROM $table"; - $result = $this->db->sql_query($sql); - - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['Field']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - return false; - break; - - // PostgreSQL has a way of doing this in a much simpler way but would - // not allow us to support all versions of PostgreSQL - case 'postgres': - $sql = "SELECT a.attname - FROM pg_class c, pg_attribute a - WHERE c.relname = '{$table}' - AND a.attnum > 0 - AND a.attrelid = c.oid"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['attname']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - - return false; - break; - - // same deal with PostgreSQL, we must perform more complex operations than - // we technically could - case 'mssql': - $sql = "SELECT c.name - FROM syscolumns c - LEFT JOIN sysobjects o ON c.id = o.id - WHERE o.name = '{$table}'"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['name']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - return false; - break; - - case 'oracle': - $sql = "SELECT column_name - FROM user_tab_columns - WHERE table_name = '{$table}'"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['column_name']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - return false; - break; - - case 'firebird': - $sql = "SELECT RDB\$FIELD_NAME as FNAME - FROM RDB\$RELATION_FIELDS - WHERE RDB\$RELATION_NAME = '{$table}'"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['fname']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - return false; - break; - - case 'db2': - $sql = "SELECT colname - FROM syscat.columns - WHERE tabname = '$table'"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - // lower case just in case - if (strtolower($row['colname']) == $column_name) - { - $this->db->sql_freeresult($result); - return true; - } - } - $this->db->sql_freeresult($result); - return false; - break; - - // ugh, SQLite - case 'sqlite': - $sql = "SELECT sql - FROM sqlite_master - WHERE type = 'table' - AND name = '{$table}'"; - $result = $this->db->sql_query($sql); - - if (!$result) - { - return false; - } - - $row = $this->db->sql_fetchrow($result); - $this->db->sql_freeresult($result); - - preg_match('#\((.*)\)#s', $row['sql'], $matches); - - $cols = trim($matches[1]); - $col_array = preg_split('/,(?![\s\w]+\))/m', $cols); - - foreach ($col_array as $declaration) - { - $entities = preg_split('#\s+#', trim($declaration)); - if ($entities[0] == 'PRIMARY') - { - continue; - } - - if (strtolower($entities[0]) == $column_name) - { - return true; - } - } - return false; - break; - } - } - - /** - * Add new column - */ - public function sql_column_add($table_name, $column_name, $column_data) - { - $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data); - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - $statements[] = 'ALTER TABLE "' . $table_name . '" ADD "' . $column_name . '" ' . $column_data['column_type_sql']; - break; - - case 'mssql': - $statements[] = 'ALTER TABLE [' . $table_name . '] ADD [' . $column_name . '] ' . $column_data['column_type_sql_default']; - break; - - case 'mysql': - $statements[] = 'ALTER TABLE `' . $table_name . '` ADD COLUMN `' . $column_name . '` ' . $column_data['column_type_sql']; - break; - - case 'oracle': - $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql']; - break; - - case 'postgres': - $statements[] = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type_sql']; - break; - - case 'db2': - $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql']; - break; - - case 'sqlite': - if (version_compare(sqlite_libversion(), '3.0') == -1) - { - $sql = "SELECT sql - FROM sqlite_master - WHERE type = 'table' - AND name = '{$table_name}' - ORDER BY type DESC, name;"; - $result = $this->db->sql_query($sql); - - if (!$result) - { - break; - } - - $row = $this->db->sql_fetchrow($result); - $this->db->sql_freeresult($result); - - $statements[] = 'begin'; - - // Create a backup table and populate it, destroy the existing one - $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']); - $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; - $statements[] = 'DROP TABLE ' . $table_name; - - preg_match('#\((.*)\)#s', $row['sql'], $matches); - - $new_table_cols = trim($matches[1]); - $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); - $column_list = array(); - - foreach ($old_table_cols as $declaration) - { - $entities = preg_split('#\s+#', trim($declaration)); - if ($entities[0] == 'PRIMARY') - { - continue; - } - $column_list[] = $entities[0]; - } - - $columns = implode(',', $column_list); - - $new_table_cols = $column_name . ' ' . $column_data['column_type_sql'] . ',' . $new_table_cols; - - // create a new table and fill it up. destroy the temp one - $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');'; - $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; - $statements[] = 'DROP TABLE ' . $table_name . '_temp'; - - $statements[] = 'commit'; - } - else - { - $statements[] = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' [' . $column_data['column_type_sql'] . ']'; - } - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Drop column - */ - public function sql_column_remove($table_name, $column_name) - { - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - $statements[] = 'ALTER TABLE "' . $table_name . '" DROP "' . $column_name . '"'; - break; - - case 'mssql': - $statements[] = 'ALTER TABLE [' . $table_name . '] DROP COLUMN [' . $column_name . ']'; - break; - - case 'mysql': - $statements[] = 'ALTER TABLE `' . $table_name . '` DROP COLUMN `' . $column_name . '`'; - break; - - case 'oracle': - $statements[] = 'ALTER TABLE ' . $table_name . ' DROP ' . $column_name; - break; - - case 'postgres': - $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN "' . $column_name . '"'; - break; - - case 'db2': - $statements[] = 'ALTER TABLE ' . $table_name . ' DROP ' . $column_name; - break; - - case 'sqlite': - if (version_compare(sqlite_libversion(), '3.0') == -1) - { - $sql = "SELECT sql - FROM sqlite_master - WHERE type = 'table' - AND name = '{$table_name}' - ORDER BY type DESC, name;"; - $result = $this->db->sql_query($sql); - - if (!$result) - { - break; - } - - $row = $this->db->sql_fetchrow($result); - $this->db->sql_freeresult($result); - - $statements[] = 'begin'; - - // Create a backup table and populate it, destroy the existing one - $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']); - $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; - $statements[] = 'DROP TABLE ' . $table_name; - - preg_match('#\((.*)\)#s', $row['sql'], $matches); - - $new_table_cols = trim($matches[1]); - $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); - $column_list = array(); - - foreach ($old_table_cols as $declaration) - { - $entities = preg_split('#\s+#', trim($declaration)); - if ($entities[0] == 'PRIMARY' || $entities[0] === $column_name) - { - continue; - } - $column_list[] = $entities[0]; - } - - $columns = implode(',', $column_list); - - $new_table_cols = $new_table_cols = preg_replace('/' . $column_name . '[^,]+(?:,|$)/m', '', $new_table_cols); - - // create a new table and fill it up. destroy the temp one - $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');'; - $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; - $statements[] = 'DROP TABLE ' . $table_name . '_temp'; - - $statements[] = 'commit'; - } - else - { - $statements[] = 'ALTER TABLE ' . $table_name . ' DROP COLUMN ' . $column_name; - } - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Drop Index - */ - public function sql_index_drop($table_name, $index_name) - { - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'mssql': - $statements[] = 'DROP INDEX ' . $table_name . '.' . $index_name; - break; - - case 'mysql': - $statements[] = 'DROP INDEX ' . $index_name . ' ON ' . $table_name; - break; - - case 'firebird': - case 'oracle': - case 'postgres': - case 'sqlite': - case 'db2': - $statements[] = 'DROP INDEX ' . $table_name . '_' . $index_name; - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Drop Table - */ - public function sql_table_drop($table_name) - { - $statements = array(); - - // the most basic operation, get rid of the table - $statements[] = 'DROP TABLE ' . $table_name; - - switch ($this->db->dbms_type) - { - case 'firebird': - $sql = 'SELECT RDB$GENERATOR_NAME as gen - FROM RDB$GENERATORS - WHERE RDB$SYSTEM_FLAG = 0 - AND RDB$GENERATOR_NAME = \'' . strtoupper($table_name) . "_GEN'"; - $result = $this->db->sql_query($sql); - - // does a generator exist? - if ($row = $this->db->sql_fetchrow($result)) - { - $statements[] = "DROP GENERATOR {$row['gen']};"; - } - $this->db->sql_freeresult($result); - break; - - case 'oracle': - $sql = 'SELECT A.REFERENCED_NAME - FROM USER_DEPENDENCIES A, USER_TRIGGERS B - WHERE A.REFERENCED_TYPE = \'SEQUENCE\' - AND A.NAME = B.TRIGGER_NAME - AND B.TABLE_NAME = \'' . strtoupper($table_name) . "'"; - $result = $this->db->sql_query($sql); - - // any sequences ref'd to this table's triggers? - while ($row = $this->db->sql_fetchrow($result)) - { - $statements[] = "DROP SEQUENCE {$row['referenced_name']}"; - } - $this->db->sql_freeresult($result); - - case 'postgres': - // PGSQL does not "tightly" bind sequences and tables, we must guess... - $sql = "SELECT relname - FROM pg_class - WHERE relkind = 'S' - AND relname = '{$table_name}_seq'"; - $result = $this->db->sql_query($sql); - - // We don't even care about storing the results. We already know the answer if we get rows back. - if ($this->db->sql_fetchrow($result)) - { - $statements[] = "DROP SEQUENCE {$table_name}_seq;\n"; - } - $this->db->sql_freeresult($result); - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Add primary key - */ - public function sql_create_primary_key($table_name, $column) - { - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - case 'postgres': - case 'mysql': - case 'db2': - $statements[] = 'ALTER TABLE ' . $table_name . ' ADD PRIMARY KEY (' . implode(', ', $column) . ')'; - break; - - case 'mssql': - $sql = "ALTER TABLE [{$table_name}] WITH NOCHECK ADD "; - $sql .= "CONSTRAINT [PK_{$table_name}] PRIMARY KEY CLUSTERED ("; - $sql .= '[' . implode("],\n\t\t[", $column) . ']'; - $sql .= ') ON [PRIMARY]'; - - $statements[] = $sql; - break; - - case 'oracle': - $statements[] = 'ALTER TABLE ' . $table_name . 'add CONSTRAINT pk_' . $table_name . ' PRIMARY KEY (' . implode(', ', $column) . ')'; - break; - - case 'sqlite': - $sql = "SELECT sql - FROM sqlite_master - WHERE type = 'table' - AND name = '{$table_name}' - ORDER BY type DESC, name;"; - $result = $this->db->sql_query($sql); - - if (!$result) - { - break; - } - - $row = $this->db->sql_fetchrow($result); - $this->db->sql_freeresult($result); - - $statements[] = 'begin'; - - // Create a backup table and populate it, destroy the existing one - $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']); - $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; - $statements[] = 'DROP TABLE ' . $table_name; - - preg_match('#\((.*)\)#s', $row['sql'], $matches); - - $new_table_cols = trim($matches[1]); - $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); - $column_list = array(); - - foreach ($old_table_cols as $declaration) - { - $entities = preg_split('#\s+#', trim($declaration)); - if ($entities[0] == 'PRIMARY') - { - continue; - } - $column_list[] = $entities[0]; - } - - $columns = implode(',', $column_list); - - // create a new table and fill it up. destroy the temp one - $statements[] = 'CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ', PRIMARY KEY (' . implode(', ', $column) . '));'; - $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; - $statements[] = 'DROP TABLE ' . $table_name . '_temp'; - - $statements[] = 'commit'; - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Add unique index - */ - public function sql_create_unique_index($table_name, $index_name, $column) - { - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - case 'postgres': - case 'oracle': - case 'sqlite': - case 'db2': - $statements[] = 'CREATE UNIQUE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; - break; - - case 'mysql': - $statements[] = 'CREATE UNIQUE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; - break; - - case 'mssql': - $statements[] = 'CREATE UNIQUE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]'; - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * Add index - */ - public function sql_create_index($table_name, $index_name, $column) - { - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - case 'postgres': - case 'oracle': - case 'sqlite': - case 'db2': - $statements[] = 'CREATE INDEX ' . $table_name . '_' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; - break; - - case 'mysql': - $statements[] = 'CREATE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ')'; - break; - - case 'mssql': - $statements[] = 'CREATE INDEX ' . $index_name . ' ON ' . $table_name . '(' . implode(', ', $column) . ') ON [PRIMARY]'; - break; - } - - return $this->_sql_run_sql($statements); - } - - /** - * List all of the indices that belong to a table, - * does not count: - * * UNIQUE indices - * * PRIMARY keys - */ - public function sql_list_index($table_name) - { - $index_array = array(); - - if ($this->db->dbms_type == 'mssql') - { - $sql = "EXEC sp_statistics '$table_name'"; - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - if ($row['TYPE'] == 3) - { - $index_array[] = $row['INDEX_NAME']; - } - } - $this->db->sql_freeresult($result); - } - else - { - switch ($this->db->dbms_type) - { - case 'firebird': - $sql = "SELECT LOWER(RDB\$INDEX_NAME) as index_name - FROM RDB\$INDICES - WHERE RDB\$RELATION_NAME = " . strtoupper($table_name) . " - AND RDB\$UNIQUE_FLAG IS NULL - AND RDB\$FOREIGN_KEY IS NULL"; - $col = 'index_name'; - break; - - case 'postgres': - $sql = "SELECT ic.relname as index_name - FROM pg_class bc, pg_class ic, pg_index i - WHERE (bc.oid = i.indrelid) - AND (ic.oid = i.indexrelid) - AND (bc.relname = '" . $table_name . "') - AND (i.indisunique != 't') - AND (i.indisprimary != 't')"; - $col = 'index_name'; - break; - - case 'mysql': - $sql = 'SHOW KEYS - FROM ' . $table_name; - $col = 'Key_name'; - break; - - case 'oracle': - $sql = "SELECT index_name - FROM user_indexes - WHERE table_name = '" . $table_name . "' - AND generated = 'N'"; - $col = 'index_name'; - break; - - case 'sqlite': - $sql = "PRAGMA index_info('" . $table_name . "');"; - $col = 'name'; - break; - - case 'db2': - $sql = "SELECT indname - FROM SYSCAT.INDEXES - WHERE TABNAME = '$table_name' - AND UNIQUERULE <> 'P'"; - $col = 'name'; - } - - $result = $this->db->sql_query($sql); - while ($row = $this->db->sql_fetchrow($result)) - { - if ($this->db->dbms_type == 'mysql' && !$row['Non_unique']) - { - continue; - } - - switch ($this->db->dbms_type) - { - case 'firebird': - case 'oracle': - case 'postgres': - case 'sqlite': - case 'db2': - $row[$col] = substr($row[$col], strlen($table_name) + 1); - break; - } - - $index_array[] = $row[$col]; - } - $this->db->sql_freeresult($result); - } - - return array_map('strtolower', $index_array); - } - - /** - * Change column type (not name!) - */ - public function sql_column_change($table_name, $column_name, $column_data) - { - $column_data = $this->sql_prepare_column_data($table_name, $column_name, $column_data); - $statements = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - // Change type... - $statements[] = 'ALTER TABLE "' . $table_name . '" ALTER COLUMN "' . $column_name . '" TYPE ' . ' ' . $column_data['column_type_sql']; - break; - - case 'mssql': - $statements[] = 'ALTER TABLE [' . $table_name . '] ALTER COLUMN [' . $column_name . '] ' . $column_data['column_type_sql']; - break; - - case 'mysql': - $statements[] = 'ALTER TABLE `' . $table_name . '` CHANGE `' . $column_name . '` `' . $column_name . '` ' . $column_data['column_type_sql']; - break; - - case 'oracle': - $statements[] = 'ALTER TABLE ' . $table_name . ' MODIFY ' . $column_name . ' ' . $column_data['column_type_sql']; - break; - - case 'db2': - $statements[] = 'ALTER TABLE ' . $table_name . ' ALTER ' . $column_name . ' SET DATA TYPE ' . $column_data['column_type_sql']; - break; - - case 'postgres': - $sql = 'ALTER TABLE ' . $table_name . ' '; - - $sql_array = array(); - $sql_array[] = 'ALTER COLUMN ' . $column_name . ' TYPE ' . $column_data['column_type']; - - if (isset($column_data['null'])) - { - if ($column_data['null'] == 'NOT NULL') - { - $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET NOT NULL'; - } - else if ($column_data['null'] == 'NULL') - { - $sql_array[] = 'ALTER COLUMN ' . $column_name . ' DROP NOT NULL'; - } - } - - if (isset($column_data['default'])) - { - $sql_array[] = 'ALTER COLUMN ' . $column_name . ' SET DEFAULT ' . $column_data['default']; - } - - // we don't want to double up on constraints if we change different number data types - if (isset($column_data['constraint'])) - { - $constraint_sql = "SELECT consrc as constraint_data - FROM pg_constraint, pg_class bc - WHERE conrelid = bc.oid - AND bc.relname = '{$table_name}' - AND NOT EXISTS ( - SELECT * - FROM pg_constraint as c, pg_inherits as i - WHERE i.inhrelid = pg_constraint.conrelid - AND c.conname = pg_constraint.conname - AND c.consrc = pg_constraint.consrc - AND c.conrelid = i.inhparent - )"; - - $constraint_exists = false; - - $result = $this->db->sql_query($constraint_sql); - while ($row = $this->db->sql_fetchrow($result)) - { - if (trim($row['constraint_data']) == trim($column_data['constraint'])) - { - $constraint_exists = true; - break; - } - } - $this->db->sql_freeresult($result); - - if (!$constraint_exists) - { - $sql_array[] = 'ADD ' . $column_data['constraint']; - } - } - - $sql .= implode(', ', $sql_array); - - $statements[] = $sql; - break; - - case 'sqlite': - $sql = "SELECT sql - FROM sqlite_master - WHERE type = 'table' - AND name = '{$table_name}' - ORDER BY type DESC, name;"; - $result = $this->db->sql_query($sql); - - if (!$result) - { - break; - } - - $row = $this->db->sql_fetchrow($result); - $this->db->sql_freeresult($result); - - $statements[] = 'begin'; - - // Create a temp table and populate it, destroy the existing one - $statements[] = preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']); - $statements[] = 'INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name; - $statements[] = 'DROP TABLE ' . $table_name; - - preg_match('#\((.*)\)#s', $row['sql'], $matches); - - $new_table_cols = trim($matches[1]); - $old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols); - $column_list = array(); - - foreach ($old_table_cols as $key => $declaration) - { - $entities = preg_split('#\s+#', trim($declaration)); - $column_list[] = $entities[0]; - if ($entities[0] == $column_name) - { - $old_table_cols[$key] = $column_name . ' ' . $column_data['column_type_sql']; - } - } - - $columns = implode(',', $column_list); - - // create a new table and fill it up. destroy the temp one - $statements[] = 'CREATE TABLE ' . $table_name . ' (' . implode(',', $old_table_cols) . ');'; - $statements[] = 'INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;'; - $statements[] = 'DROP TABLE ' . $table_name . '_temp'; - - $statements[] = 'commit'; - - break; - } - - return $this->_sql_run_sql($statements); - } - - private function _sql_get_special_row($value, &$data) - { - if (is_array($value)) - { - if (isset($value['auto_increment'])) - { - $auto_key = explode(':', $value['auto_increment'], 2); - $value_key = $auto_key[0]; - $auto_key = (int) $auto_key[1]; - - if (isset($this->stored_increments[$value_key][$auto_key])) - { - $value = $this->stored_increments[$value_key][$auto_key]; - } - } - else - { - $value = NULL; - } - } - else if (strpos($value, '{') === 0 && strpos($value, '}') === strlen($value) - 1) - { - if (strpos($value, '{L_') === 0 && isset(phpbb::$user->lang[substr($value, 3, -1)])) - { - $value = phpbb::$user->lang[substr($value, 3, -1)]; - } - else if (isset($data[substr($value, 1, -1)])) - { - $value = $data[substr($value, 1, -1)]; - } - } - - return $value; - } - - /** - * Private method for performing sql statements (either execute them or return them) - * @access private - */ - private function _sql_run_sql($statements) - { - if ($this->return_statements) - { - return $statements; - } - - // We could add error handling here... - foreach ($statements as $sql) - { - if ($sql === 'begin') - { - $this->db->sql_transaction('begin'); - } - else if ($sql === 'commit') - { - $this->db->sql_transaction('commit'); - } - else - { - $this->db->sql_query($sql); - } - } - - return true; - } - - /** - * Function to prepare some column information for better usage - * @access private - */ - private function sql_prepare_column_data($table_name, $column_name, $column_data) - { - // Get type - if (strpos($column_data[0], ':') !== false) - { - list($orig_column_type, $column_length) = explode(':', $column_data[0]); - - if (!is_array($this->db->dbms_type_map[$orig_column_type . ':'])) - { - $column_type = sprintf($this->db->dbms_type_map[$orig_column_type . ':'], $column_length); - } - else - { - if (isset($this->db->dbms_type_map[$orig_column_type . ':']['rule'])) - { - switch ($this->db->dbms_type_map[$orig_column_type . ':']['rule'][0]) - { - case 'div': - $column_length /= $this->db->dbms_type_map[$orig_column_type . ':']['rule'][1]; - $column_length = ceil($column_length); - $column_type = sprintf($this->db->dbms_type_map[$orig_column_type . ':'][0], $column_length); - break; - } - } - - if (isset($this->db->dbms_type_map[$orig_column_type . ':']['limit'])) - { - switch ($this->db->dbms_type_map[$orig_column_type . ':']['limit'][0]) - { - case 'mult': - $column_length *= $this->db->dbms_type_map[$orig_column_type . ':']['limit'][1]; - if ($column_length > $this->db->dbms_type_map[$orig_column_type . ':']['limit'][2]) - { - $column_type = $this->db->dbms_type_map[$orig_column_type . ':']['limit'][3]; - } - else - { - $column_type = sprintf($this->db->dbms_type_map[$orig_column_type . ':'][0], $column_length); - } - break; - } - } - } - - $orig_column_type .= ':'; - } - else - { - $orig_column_type = $column_data[0]; - $column_type = $this->db->dbms_type_map[$column_data[0]]; - } - - // Adjust default value if db-dependant specified - if (is_array($column_data[1])) - { - $column_data[1] = (isset($column_data[1][$this->db->dbms_type])) ? $column_data[1][$this->db->dbms_type] : $column_data[1]['default']; - } - - $sql = ''; - - $return_array = array(); - - switch ($this->db->dbms_type) - { - case 'firebird': - $sql .= " {$column_type} "; - - if (!is_null($column_data[1])) - { - $sql .= 'DEFAULT ' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' '; - } - - $sql .= 'NOT NULL'; - - // This is a UNICODE column and thus should be given it's fair share - if (preg_match('/^X?STEXT_UNI|VCHAR_(CI|UNI:?)/', $column_data[0])) - { - $sql .= ' COLLATE UNICODE'; - } - - $return_array['auto_increment'] = false; - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { - $return_array['auto_increment'] = true; - } - - break; - - case 'mssql': - $sql .= " {$column_type} "; - $sql_default = " {$column_type} "; - - // For adding columns we need the default definition - if (!is_null($column_data[1])) - { - // For hexadecimal values do not use single quotes - if (strpos($column_data[1], '0x') === 0) - { - $sql_default .= 'DEFAULT (' . $column_data[1] . ') '; - } - else - { - $sql_default .= 'DEFAULT (' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ') '; - } - } - - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { -// $sql .= 'IDENTITY (1, 1) '; - $sql_default .= 'IDENTITY (1, 1) '; - } - - $return_array['textimage'] = $column_type === '[text]'; - - $sql .= 'NOT NULL'; - $sql_default .= 'NOT NULL'; - - $return_array['column_type_sql_default'] = $sql_default; - break; - - case 'mysql': - $sql .= " {$column_type} "; - - // For hexadecimal values do not use single quotes - if (!is_null($column_data[1]) && substr($column_type, -4) !== 'text' && substr($column_type, -4) !== 'blob') - { - $sql .= (strpos($column_data[1], '0x') === 0) ? "DEFAULT {$column_data[1]} " : "DEFAULT '{$column_data[1]}' "; - } - $sql .= 'NOT NULL'; - - if (isset($column_data[2])) - { - if ($column_data[2] == 'auto_increment') - { - $sql .= ' auto_increment'; - } - else if ($column_data[2] == 'true_sort') - { - $sql .= ' COLLATE utf8_unicode_ci'; - } - } - - break; - - case 'oracle': - $sql .= " {$column_type} "; - $sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : ''; - - // In Oracle empty strings ('') are treated as NULL. - // Therefore in oracle we allow NULL's for all DEFAULT '' entries - // Oracle does not like setting NOT NULL on a column that is already NOT NULL (this happens only on number fields) - if (!preg_match('/number/i', $column_type)) - { - $sql .= ($column_data[1] === '') ? '' : 'NOT NULL'; - } - - $return_array['auto_increment'] = false; - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { - $return_array['auto_increment'] = true; - } - break; - - case 'postgres': - $return_array['column_type'] = $column_type; - - $sql .= " {$column_type} "; - - $return_array['auto_increment'] = false; - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { - $default_val = "nextval('{$table_name}_seq')"; - $return_array['auto_increment'] = true; - } - else if (!is_null($column_data[1])) - { - $default_val = "'" . $column_data[1] . "'"; - $return_array['null'] = 'NOT NULL'; - $sql .= 'NOT NULL '; - } - - $return_array['default'] = $default_val; - - $sql .= "DEFAULT {$default_val}"; - - // Unsigned? Then add a CHECK contraint - if (in_array($orig_column_type, $this->unsigned_types)) - { - $return_array['constraint'] = "CHECK ({$column_name} >= 0)"; - $sql .= " CHECK ({$column_name} >= 0)"; - } - break; - - case 'sqlite': - $return_array['primary_key_set'] = false; - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { - $sql .= ' INTEGER PRIMARY KEY'; - $return_array['primary_key_set'] = true; - } - else - { - $sql .= ' ' . $column_type; - } - - $sql .= ' NOT NULL '; - $sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}'" : ''; - break; - - case 'db2': - $sql .= " {$column_type} NOT NULL"; - - if (isset($column_data[2]) && $column_data[2] == 'auto_increment') - { - $sql .= ' GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1)'; - } - else - { - if (preg_match('/^(integer|smallint|float)$/', $column_type)) - { - $sql .= " DEFAULT {$column_data[1]}"; - } - else - { - $sql .= " DEFAULT '{$column_data[1]}'"; - } - } - break; - } - - $return_array['column_type_sql'] = $sql; - - return $return_array; - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/dbal.php b/phpBB/includes/db/dbal.php deleted file mode 100644 index 15127509cc..0000000000 --- a/phpBB/includes/db/dbal.php +++ /dev/null @@ -1,1553 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* DBAL Factory -* Only used to instantiate a new DB object -* -* @package dbal -* @static -*/ -abstract class phpbb_db_dbal -{ - /** - * Get new database object - * - * @param string $dbms Database module to call - * @return object Database object - * @access public - */ - public static function new_instance($dbms) - { - $class = 'phpbb_dbal_' . $dbms; - - if (!class_exists($class)) - { - include PHPBB_ROOT_PATH . 'includes/db/' . $dbms . '.' . PHP_EXT; - } - - // Instantiate class - $db = new $class(); - - // Fill default sql layer - $db->sql_layer = $dbms; - - return $db; - } - - /** - * Get new database object and connect to database - * - * @param string $dbms Database module to call - * @param string $server DB server address to connect to - * @param string $user DB user name - * @param string $password DB password to use - * @param string $database Database name to connect to - * @param int $port DB Port - * @param bool $persistency Open persistent DB connection if true - * @param bool $new_link If set to true a new connection is opened instead of re-using old connections - * - * @return object Database object - * @access public - */ - public static function connect($dbms, $server, $user, $password, $database, $port = false, $persistency = false, $new_link = false) - { - $class = 'phpbb_dbal_' . $dbms; - - if (!class_exists($class)) - { - include PHPBB_ROOT_PATH . 'includes/db/' . $dbms . '.' . PHP_EXT; - } - - // Instantiate class - $db = new $class(); - - // Fill default sql layer - $db->sql_layer = $dbms; - - // Connect to DB - $db->sql_connect($server, $user, $password, $database, $port, $persistency, $new_link); - - // Return db object - return $db; - } -} - -/** -* Database Abstraction Layer -* @package dbal -*/ -abstract class phpbb_dbal -{ - /** - * @var array required phpBB objects - */ - public $phpbb_required = array('config'); - - /** - * @var array Optional phpBB objects - */ - public $phpbb_optional = array('acm', 'user', 'acl'); - - /** - * @var string Current sql layer name - */ - public $sql_layer = ''; - - /** - * @var string Exact version of the DBAL, directly queried - */ - public $sql_server_version = false; - - /** - * @var mixed Database connection id/resource - */ - public $db_connect_id; - - /** - * @var mixed Database query result id/resource - */ - public $query_result; - - /** - * @var bool Persistent connection - */ - public $persistency = false; - - /** - * @var string DB user name - */ - public $user = ''; - - /** - * @var string DB server address connected to - */ - public $server = ''; - - /** - * @var string Database name connected to - */ - public $dbname = ''; - - /** - * @var int Database port used - */ - public $port = 0; - - /** - * @var bool Is true if in transaction - */ - public $transaction = false; - - /** - * @var int Holding transaction count - */ - public $transactions = 0; - - /** - * Stores number of queries - * - * Keys are: - * <ul> - * <li>cached: Number of cached queries executed</li> - * <li>normal: Number of non-cached queries executed</li> - * <li>total: Total number of queries executed</li> - * </ul> - * - * @var array - */ - public $num_queries = array(); - - /** - * Stores opened queries. - * - * The key is returned by {@link phpbb_dbal::sql_get_result_key() sql_get_result_key()}. - * The value is the {@link phpbb_dbal::$query_result Database query result id/resource}. - * - * @var array - */ - public $open_queries = array(); - - /** - * @var string Wildcard for matching any (%) character within LIKE expressions - */ - public $any_char; - - /** - * @var string Wildcard for matching exactly one (_) character within LIKE expressions - */ - public $one_char; - - /** - * @var array Storing cached result rowset - */ - protected $cache_rowset = array(); - - /** - * @var int Storing cached result rowset index - */ - protected $cache_index = 0; - - /** - * @var bool If true then methods do not call {@link phpbb_dbal::sql_error() sql_error()} on SQL error, but return silently. - */ - public $return_on_error = false; - - /** - * @var bool This is set to true if an error had been triggered. - */ - public $sql_error_triggered = false; - - /** - * @var string Holds the last sql query on triggered sql error. - */ - public $sql_error_sql = ''; - - /** - * @var array Holds the SQL error information - only populated if {@link phpbb_dbal::$sql_error_triggered sql_error_triggered} is set to true. - */ - public $sql_error_returned = array(); - - /** - * Database features - * - * <ul> - * <li>multi_insert: Supports multi inserts</li> - * <li>count_distinct: Supports COUNT(DISTINGT ...)</li> - * <li>multi_table_deletion: Supports multiple table deletion</li> - * <li>truncate: Supports table truncation</li> - * </ul> - * - * @var array - */ - public $features = array( - 'multi_insert' => true, - 'count_distinct' => true, - 'multi_table_deletion' => true, - 'truncate' => true, - ); - - /** - * @var int Passed time for executing SQL queries - */ - public $sql_time = 0; - - /** - * @var int Current timestamp - */ - public $curtime = 0; - - /**#@+ - * @var string String to hold information for {@link phpbb_dbal::sql_report() SQL report}. - */ - protected $query_hold = ''; - protected $html_hold = ''; - protected $sql_report = ''; - /**#@-*/ - - /** - * Constructor. Set default values. - * @access public - */ - public function __construct() - { - $this->num_queries = array( - 'cached' => 0, - 'normal' => 0, - 'total' => 0, - ); - - // Do not change this please! This variable is used to easy the use of it - and is hardcoded. - $this->any_char = chr(0) . '%'; - $this->one_char = chr(0) . '_'; - - $this->cache_rowset = array(); - $this->cache_index = 0; - } - - /** - * Connect to SQL Server. - * - * @param string $server DB server address to connect to - * @param string $user DB user name - * @param string $password DB password to use - * @param string $database Database name to connect to - * @param int $port DB Port - * @param bool $persistency Open persistent DB connection if true - * @param bool $new_link If set to true a new connection is opened instead of re-using old connections - * - * @return mixed Database connection id/resource - * @access public - */ - abstract public function sql_connect($server, $user, $password, $database, $port = false, $persistency = false , $new_link = false); - - /** - * Version information about used database - * - * @param bool $raw If true, only return the fetched sql_server_version without any additional strings - * - * @return string Sql server version - * @access public - */ - abstract public function sql_server_info($raw = false); - - /** - * Return number of affected rows. - * - * @return int Number of affected rows. False if there is no valid database connection id. - * @access public - */ - abstract public function sql_affectedrows(); - - /** - * Get last inserted id after insert statement - * - * @return int Last inserted id. False if there is no valid database connection id. - * @access public - */ - abstract public function sql_nextid(); - - /** - * Escape string used in sql query. - * - * @param string $msg Text to escape - * - * @return string Escaped text - * @access public - */ - abstract public function sql_escape($msg); - - /** - * Expose a DBMS specific function. - * - * Supported types are: - * <ul> - * <li>length_varchar: Get expression to return length of VARCHAR</li> - * <li>length_text: Get expression to return length of TEXT</li> - * </ul> - * - * @param string $type Type to return DB-specific code for - * @param string $col Column name to operate on - * - * @return string DB-specific code able to be used in SQL query - * @access public - */ - abstract public function sql_function($type, $col); - - /** - * Handle data by using prepared statements. - * - * @param string $type The type to handle. Possible values are: INSERT, UPDATE - * @param string $table The table to use insert or update - * @param mixed $data The data to insert/update in an array (key == column, value == value) - * @param string $where An optional where-statement - * @access public - * @todo implement correctly by using types and only overwrite if DB supports prepared statements - */ - public function sql_handle_data($type, $table, $data, $where = '') - { - if ($type === 'UPDATE') - { - $where = ($where) ? ' WHERE ' . $where : ''; - $this->sql_query('UPDATE ' . $table . ' SET ' . $this->sql_build_array('UPDATE', $data) . $where); - } - else - { - $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $data)); - } - } - - /** - * DB-specific base query method. Called by {@link phpbb_dbal::sql_query() sql_query()}. - * - * @param string $query Contains the SQL query which shall be executed - * - * @return mixed Returns the query result resource. When casted to bool the returned value returns true on success and false on failure - * @access protected - */ - abstract protected function _sql_query($query); - - /** - * DB-specific method to Build LIMIT query and run it. Called by {@link phpbb_dbal::sql_query_limit() sql_query_limit}. - * - * @param string $query SQL query LIMIT should be applied to - * @param int $total Total number of rows returned - * @param int $offset Offset to read from - * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache - * - * @return mixed Returns the query result resource. When casted to bool the returned value returns true on success and false on failure - * @access protected - */ - abstract protected function _sql_query_limit($query, $total, $offset, $cache_ttl); - - /** - * DB-specific method to close sql connection. Called by {@link phpbb_dbal::sql_close() sql_close()}. - * @access protected - */ - abstract protected function _sql_close(); - - /** - * DB-specific SQL Transaction. Called by {@link phpbb_dbal::sql_transaction() sql_transaction()}. - * - * @param string $status The status code. See {@link phpbb_dbal::sql_transaction() sql_transaction()} for status codes. - * - * @return mixed The result returned by the DB - * @access protected - */ - abstract protected function _sql_transaction($status); - - /** - * Fetch current row. Called by {@link phpbb_dbal::sql_fetchrow() sql_fetchrow()}. - * - * @param mixed $query_id Query result resource - * - * @return array|bool The current row or false if an error occurred - * @access protected - */ - abstract protected function _sql_fetchrow($query_id); - - /** - * Free query result. Called by {@link phpbb_dbal::sql_freeresult() sql_freeresult()}. - * - * @param mixed $query_id Query result resource - * - * @return mixed The DB result - * @access protected - */ - abstract protected function _sql_freeresult($query_id); - - /** - * Correctly adjust LIKE expression for special characters. Called by {@link phpbb_dbal::sql_like_expression() sql_like_expression()}. - * - * @param string $expression The expression to use. Every wildcard is escaped, except {@link phpbb_dbal::$any_char $any_char} and {@link phpbb_dbal::$one_char $one_char} - * - * @return string LIKE expression including the keyword! - * @access protected - */ - abstract protected function _sql_like_expression($expression); - - /** - * Build DB-specific query bits for {@link phpbb_dbal::sql_build_query() sql_build_query()}. - * - * Currently used stages are ($stage: $data) - * <ul> - * <li>FROM: implode(', ', $table_array)</li> - * <li>WHERE: Full WHERE-Statement without WHERE keyword</li> - * </ul> - * - * @param string $stage The current stage build_query needs db-specific data for. Currently used are: FROM and WHERE. - * @param string $data Data to operate with - * - * @return string $data in it's original form or adjusted to meet DB-specific standard - * @access protected - */ - abstract protected function _sql_custom_build($stage, $data); - - /** - * Return sql error array. Called by {@link phpbb_dbal::sql_error() sql_error()}. - * - * @return array Array with two keys. 'code' for the error code and 'message' for the error message. - * @access protected - */ - abstract protected function _sql_error(); - - /** - * Run DB-specific code to build SQL Report to explain queries, show statistics and runtime information. Called by {@link phpbb_dbal::sql_report() sql_report()}. - * - * This function only executes if the GET parameter 'explain' is true and phpbb::$base_config['debug_extra'] enabled. - * - * @param string $mode The mode to handle. 'display' is used for displaying the report, all other modes are internal. - * @param string $query Query to document/explain. Only used internally to build the plan. - * - * @access protected - */ - abstract protected function _sql_report($mode, $query = ''); - - /** - * 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 Returns the query result resource. When casted to bool the returned value returns true on success and false on failure - * @access public - */ - public function sql_query($query = '', $cache_ttl = 0) - { - if (empty($query)) - { - return false; - } - - // EXPLAIN only in extra debug mode - if (phpbb::$base_config['debug_extra']) - { - $this->sql_report('start', $query); - } - - $this->query_result = false; - - if ($cache_ttl) - { - $this->sql_get_cache($query); - } - - $this->sql_add_num_queries($this->query_result); - - if ($this->query_result !== false) - { - if (phpbb::$base_config['debug_extra']) - { - $this->sql_report('fromcache', $query); - } - - return $this->query_result; - } - - if (($this->query_result = $this->_sql_query($query)) === false) - { - $this->sql_error($query); - } - - if (phpbb::$base_config['debug_extra']) - { - $this->sql_report('stop', $query); - } - - if ($cache_ttl) - { - $this->sql_put_cache($query, $cache_ttl); - } - - if ($cache_ttl || strpos($query, 'SELECT') === 0) - { - if (($key = $this->sql_get_result_key($this->query_result)) !== false) - { - $this->open_queries[$key] = $this->query_result; - } - } - - return $this->query_result; - } - - /** - * Build LIMIT query and run it. - * - * @param string $query SQL query LIMIT should be applied to - * @param int $total Total number of rows returned - * @param int $offset Offset to read from - * @param int $cache_ttl Either 0 to avoid caching or the time in seconds which the result shall be kept in cache - * - * @return mixed Returns the query result resource. When casted to bool the returned value returns true on success and false on failure - * @access public - */ - public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) - { - if (empty($query)) - { - return false; - } - - // Never use a negative total or offset - $total = ($total < 0) ? 0 : $total; - $offset = ($offset < 0) ? 0 : $offset; - - return $this->_sql_query_limit($query, $total, $offset, $cache_ttl); - } - - /** - * Switch for "return on error" or "display error message". Affects {@link phpbb_dbal::$return_on_error $return_on_error}. - * - * @param bool $fail True to return on SQL error. False to display error message on SQL error. - * @access public - */ - public function sql_return_on_error($fail = false) - { - $this->sql_error_triggered = false; - $this->sql_error_sql = ''; - - $this->return_on_error = $fail; - } - - /** - * Return number of sql queries and cached sql queries used. - * - * @param bool $cached True to return cached queries executed. False to return non-cached queries executed. - * - * @return int Number of queries executed - * @access public - */ - public function sql_num_queries($cached = false) - { - return ($cached) ? $this->num_queries['cached'] : $this->num_queries['normal']; - } - - /** - * DBAL garbage collection, close sql connection. - * - * Iterates through {@link phpbb_dbal::$open_queries open queries} and closes them. - * For connection close {@link phpbb_dbal::_sql_close() the DB-specific method} is called. - * - * @return bool False if there was no db connection to close or an error occurred, else true - * @access public - */ - public function sql_close() - { - if (!$this->db_connect_id) - { - return false; - } - - if ($this->transaction) - { - do - { - $this->sql_transaction('commit'); - } - while ($this->transaction); - } - - foreach ($this->open_queries as $key => $query_result) - { - $this->sql_freeresult($query_result); - } - - // Connection closed correctly. Set db_connect_id to false to prevent errors - if ($result = $this->_sql_close()) - { - $this->db_connect_id = false; - } - - return $result; - } - - /** - * SQL Transaction. - * - * Standard status codes are: - * <ul> - * <li>begin: Begin transaction</li> - * <li>commit: Commit/end transaction</li> - * <li>rollback: Rollback transaction</li> - * </ul> - * - * @param string $status The status code. - * - * @return mixed The result returned by the DB - * @access public - */ - public function sql_transaction($status = 'begin') - { - switch ($status) - { - case 'begin': - // If we are within a transaction we will not open another one, but enclose the current one to not loose data (prevening auto commit) - if ($this->transaction) - { - $this->transactions++; - return true; - } - - $result = $this->_sql_transaction('begin'); - - if (!$result) - { - $this->sql_error(); - } - - $this->transaction = true; - break; - - case 'commit': - // If there was a previously opened transaction we do not commit yet... but count back the number of inner transactions - if ($this->transaction && $this->transactions) - { - $this->transactions--; - return true; - } - - // Check if there is a transaction (no transaction can happen if there was an error, with a combined rollback and error returning enabled) - // This implies we have transaction always set for autocommit db's - if (!$this->transaction) - { - return false; - } - - $result = $this->_sql_transaction('commit'); - - if (!$result) - { - $this->sql_error(); - } - - $this->transaction = false; - $this->transactions = 0; - break; - - case 'rollback': - $result = $this->_sql_transaction('rollback'); - $this->transaction = false; - $this->transactions = 0; - break; - - default: - $result = $this->_sql_transaction($status); - break; - } - - return $result; - } - - /** - * Fetch current row. - * - * @param mixed $query_id Query result resource - * - * @return array|bool The current row or false if an error occurred - * @access public - */ - public function sql_fetchrow($query_id = false) - { - if ($query_id === false) - { - $query_id = $this->query_result; - } - - if ($this->sql_cache_exists($query_id)) - { - return $this->sql_cache_fetchrow($query_id); - } - - return ($query_id !== false) ? $this->_sql_fetchrow($query_id) : false; - } - - /** - * Fetch rowset (all rows). - * - * @param mixed $query_id Query result resource - * - * @return array|bool The complete rowset or false if an error occurred - * @access public - */ - public function sql_fetchrowset($query_id = false) - { - if ($query_id === false) - { - $query_id = $this->query_result; - } - - if ($query_id !== false) - { - $result = array(); - while ($row = $this->sql_fetchrow($query_id)) - { - $result[] = $row; - } - - return $result; - } - - return false; - } - - /** - * Fetch field from current row. - * - * @param string $field Field/Column name to fetch data from. - * @param mixed $query_id Query result resource - * - * @return mixed The fields value - * @access public - */ - public function sql_fetchfield($field, $query_id = false) - { - if ($query_id === false) - { - $query_id = $this->query_result; - } - - if ($query_id !== false) - { - if ($this->sql_cache_exists($query_id)) - { - return $this->sql_cache_fetchfield($query_id, $field); - } - - $row = $this->sql_fetchrow($query_id); - return (isset($row[$field])) ? $row[$field] : false; - } - - return false; - } - - /** - * Free query result. - * - * @param mixed $query_id Query result resource - * - * @return mixed The DB result - * @access public - */ - public function sql_freeresult($query_id) - { - if ($query_id === false) - { - $query_id = $this->query_result; - } - - if ($this->sql_cache_exists($query_id)) - { - return $this->sql_cache_freeresult($query_id); - } - - if (($key = $this->sql_get_result_key($query_id)) !== false) - { - unset($this->open_queries[$key]); - } - - return $this->_sql_freeresult($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters, some DBMS are handling them in a different way. - * - * @param string $expression The expression to use. Every wildcard is escaped, except {@link phpbb_dbal::$any_char $any_char} and {@link phpbb_dbal::$one_char $one_char} - * - * @return string LIKE expression including the keyword! - * @access public - */ - public function sql_like_expression($expression) - { - $expression = str_replace(array('_', '%'), array("\_", "\%"), $expression); - $expression = str_replace(array(chr(0) . "\_", chr(0) . "\%"), array('_', '%'), $expression); - - return $this->_sql_like_expression('LIKE \'' . $this->sql_escape($expression) . '\''); - } - - /** - * Build sql statement from array for insert/update/select statements. - * - * Idea for this from Ikonboard - * Possible query values: INSERT, INSERT_SELECT, UPDATE, SELECT - * - * @param string $mode The mode to handle - * @param array $assoc_ary The SQL array to insert/update/select (key == column, value == data) - * - * @return string Query able to be used in SQL queries - * @access public - */ - public function sql_build_array($mode, $assoc_ary = false) - { - if (!is_array($assoc_ary)) - { - return false; - } - - $fields = $values = array(); - $query = ''; - - if ($mode == 'INSERT' || $mode == 'INSERT_SELECT') - { - foreach ($assoc_ary as $key => $var) - { - $fields[] = $key; - - if (is_array($var) && is_string($var[0])) - { - // This is used for INSERT_SELECT(s) - $values[] = $var[0]; - } - else - { - $values[] = $this->_sql_validate_value($var); - } - } - - $query = ($mode == 'INSERT') ? ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')' : ' (' . implode(', ', $fields) . ') SELECT ' . implode(', ', $values) . ' '; - } - else if ($mode == 'MULTI_INSERT') - { - trigger_error('The MULTI_INSERT query value is no longer supported. Please use sql_multi_insert() instead.', E_USER_ERROR); - } - else if ($mode == 'UPDATE' || $mode == 'SELECT') - { - foreach ($assoc_ary as $key => $var) - { - $values[] = "$key = " . $this->_sql_validate_value($var); - } - $query = implode(($mode == 'UPDATE') ? ', ' : ' AND ', $values); - } - - return $query; - } - - /** - * Build IN or NOT IN sql comparison string, uses <> or = on single element to improve comparison speed - * - * @param string $field Name of the sql column that shall be compared - * @param array $array Array of values that are allowed (IN) or not allowed (NOT IN) - * @param bool $negate True for NOT IN (), false for IN () (default) - * @param bool $allow_empty_set If true, allow $array to be empty - this function will return 1=1 or 1=0 then. - * - * @return string SQL statement able to be used in SQL queries - * @access public - */ - public function sql_in_set($field, $array, $negate = false, $allow_empty_set = false) - { - if (!sizeof($array)) - { - if (!$allow_empty_set) - { - // Print the backtrace to help identifying the location of the problematic code - $this->sql_error('No values specified for SQL IN comparison'); - } - else - { - // NOT IN () actually means everything so use a tautology - if ($negate) - { - return '1=1'; - } - // IN () actually means nothing so use a contradiction - else - { - return '1=0'; - } - } - } - - if (!is_array($array)) - { - $array = array($array); - } - - if (sizeof($array) == 1) - { - @reset($array); - $var = current($array); - - return $field . ($negate ? ' <> ' : ' = ') . $this->_sql_validate_value($var); - } - else - { - return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', array_map(array($this, '_sql_validate_value'), $array)) . ')'; - } - } - - /** - * Run more than one insert statement. - * - * @param string $table Table name to run the statements on - * @param array &$sql_ary Multi-dimensional array holding the statement data. - * - * @return bool False if no statements were executed. - * @access public - * @todo use sql_prepare_data() - */ - public function sql_multi_insert($table, &$sql_ary) - { - if (!sizeof($sql_ary)) - { - return false; - } - - if ($this->features['multi_insert']) - { - $ary = array(); - foreach ($sql_ary as $id => $_sql_ary) - { - // If by accident the sql array is only one-dimensional we build a normal insert statement - if (!is_array($_sql_ary)) - { - $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $sql_ary)); - return true; - } - - $values = array(); - foreach ($_sql_ary as $key => $var) - { - $values[] = $this->_sql_validate_value($var); - } - $ary[] = '(' . implode(', ', $values) . ')'; - } - - $this->sql_query('INSERT INTO ' . $table . ' ' . ' (' . implode(', ', array_keys($sql_ary[0])) . ') VALUES ' . implode(', ', $ary)); - } - else - { - foreach ($sql_ary as $ary) - { - if (!is_array($ary)) - { - return false; - } - - $this->sql_query('INSERT INTO ' . $table . ' ' . $this->sql_build_array('INSERT', $ary)); - } - } - - return true; - } - - /** - * Build sql statement from array for select and select distinct statements - * - * @todo add more in-depth explanation about all possible array keys and their effects. - * - * @param string $query Query value. Possible query values: SELECT, SELECT_DISTINCT - * @param string $array Array to build statement from - * - * @return string SQL Statement - * @access public - */ - public function sql_build_query($query, $array) - { - $sql = ''; - switch ($query) - { - case 'SELECT': - case 'SELECT_DISTINCT'; - - $sql = str_replace('_', ' ', $query) . ' ' . $array['SELECT'] . ' FROM '; - - $table_array = array(); - foreach ($array['FROM'] as $table_name => $alias) - { - if (is_array($alias)) - { - foreach ($alias as $multi_alias) - { - $table_array[] = $table_name . ' ' . $multi_alias; - } - } - else - { - $table_array[] = $table_name . ' ' . $alias; - } - } - - $sql .= $this->_sql_custom_build('FROM', implode(', ', $table_array)); - - if (!empty($array['LEFT_JOIN'])) - { - foreach ($array['LEFT_JOIN'] as $join) - { - $sql .= ' LEFT JOIN ' . key($join['FROM']) . ' ' . current($join['FROM']) . ' ON (' . $join['ON'] . ')'; - } - } - - if (!empty($array['WHERE'])) - { - $sql .= ' WHERE ' . $this->_sql_custom_build('WHERE', $array['WHERE']); - } - - if (!empty($array['GROUP_BY'])) - { - $sql .= ' GROUP BY ' . $array['GROUP_BY']; - } - - if (!empty($array['ORDER_BY'])) - { - $sql .= ' ORDER BY ' . $array['ORDER_BY']; - } - - break; - } - - return $sql; - } - - /** - * Display SQL Error message. - * - * The DB-specific information is retrieved by {@link phpbb_dbal::_sql_error() _sql_error()}. - * - * @param string $sql SQL statement which triggered the error - * - * @return mixed Returns sql error array if {@link phpbb_dbal::$return_on_error $return_on_error} is true. Else script is halted. - * @access public - */ - public function sql_error($sql = '') - { - // Set var to retrieve errored status - $this->sql_error_triggered = true; - $this->sql_error_sql = $sql; - - $this->sql_error_returned = $this->_sql_error(); - - if (!$this->return_on_error) - { - $sql_message = $this->sql_error_returned['message']; - $sql_code = $this->sql_error_returned['code']; - - $message = 'SQL ERROR [ ' . $this->sql_layer . ' ]' . (($sql_message) ? '<br /><br />' . $sql_message : '') . (($sql_code) ? ' [' . $sql_code . ']' : ''); - - // Show complete SQL error and path to administrators only - // Additionally show complete error on installation or if extended debug mode is enabled - // The phpbb::$base_config['debug_extra'] variable is for development only! - if ((phpbb::registered('acl') && phpbb::$acl->acl_get('a_')) || defined('IN_INSTALL') || phpbb::$base_config['debug_extra']) - { - $message .= ($sql) ? '<br /><br />SQL<br /><br />' . htmlspecialchars($sql) : ''; - $message .= '<br />'; - } - else - { - // If error occurs in initiating the session we need to use a pre-defined language string - // This could happen if the connection could not be established for example (then we are not able to grab the default language) - if (!phpbb::registered('user')) - { - $message .= '<br /><br />An sql error occurred while fetching this page. Please contact an administrator if this problem persists.'; - } - else - { - if (!empty(phpbb::$config['board_contact'])) - { - $message .= '<br /><br />' . phpbb::$user->lang('SQL_ERROR_OCCURRED', '<a href="mailto:' . htmlspecialchars(phpbb::$config['board_contact']) . '">', '</a>'); - } - else - { - $message .= '<br /><br />' . phpbb::$user->lang('SQL_ERROR_OCCURRED', '', ''); - } - } - } - - if ($this->transaction) - { - $this->sql_transaction('rollback'); - } - - if (strlen($message) > 1024) - { - // We need to define $msg_long_text here to circumvent text stripping. - global $msg_long_text; - $msg_long_text = $message; - - trigger_error(false, E_USER_ERROR); - } - - trigger_error($message, E_USER_ERROR); - } - - if ($this->transaction) - { - $this->sql_transaction('rollback'); - } - - return $this->sql_error_returned; - } - - /** - * Build SQL Report to explain queries, show statistics and runtime information. - * - * This function only executes if the GET parameter 'explain' is true and phpbb::$base_config['debug_extra'] enabled. - * - * @param string $mode The mode to handle. 'display' is used for displaying the report, all other modes are internal. - * @param string $query Query to document/explain. Only used internally to build the plan. - * - * @access public - */ - public function sql_report($mode, $query = '') - { - global $starttime; - - if (!phpbb_request::variable('explain', false)) - { - return false; - } - - if (!$query && $this->query_hold != '') - { - $query = $this->query_hold; - } - - switch ($mode) - { - case 'display': - $this->sql_close(); - - if (phpbb::registered('acm')) - { - phpbb::$acm->unload(); - } - - $mtime = explode(' ', microtime()); - $totaltime = $mtime[0] + $mtime[1] - $starttime; - - echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> - <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> - <head> - <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> - <meta http-equiv="Content-Style-Type" content="text/css" /> - <meta http-equiv="imagetoolbar" content="no" /> - <title>SQL Report</title> - <link href="' . PHPBB_ROOT_PATH . 'adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" /> - </head> - <body id="errorpage"> - <div id="wrap"> - <div id="page-header"> - <a href="' . phpbb::$url->build_url('explain') . '">Return to previous page</a> - </div> - <div id="page-body"> - <div id="acp"> - <div class="panel"> - <span class="corners-top"><span></span></span> - <div id="content"> - <h1>SQL Report</h1> - <br /> - <p><b>Page generated in ' . round($totaltime, 4) . " seconds with {$this->num_queries['normal']} queries" . (($this->num_queries['cached']) ? " + {$this->num_queries['cached']} " . (($this->num_queries['cached'] == 1) ? 'query' : 'queries') . ' returning data from cache' : '') . '</b></p> - - <p>Time spent on ' . $this->sql_layer . ' queries: <b>' . round($this->sql_time, 5) . 's</b> | Time spent on PHP: <b>' . round($totaltime - $this->sql_time, 5) . 's</b></p> - - <br /><br /> - ' . $this->sql_report . ' - </div> - <span class="corners-bottom"><span></span></span> - </div> - </div> - </div> - <div id="page-footer"> - Powered by phpBB © 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a> - </div> - </div> - </body> - </html>'; - - exit_handler(); - - break; - - case 'stop': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $this->sql_report .= ' - - <table cellspacing="1"> - <thead> - <tr> - <th>Query #' . $this->num_queries['total'] . '</th> - </tr> - </thead> - <tbody> - <tr> - <td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td> - </tr> - </tbody> - </table> - - ' . $this->html_hold . ' - - <p style="text-align: center;"> - '; - - if ($this->query_result) - { - if (preg_match('/^(UPDATE|DELETE|REPLACE)/', $query)) - { - $this->sql_report .= 'Affected rows: <b>' . $this->sql_affectedrows($this->query_result) . '</b> | '; - } - $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed: <b>' . sprintf('%.5f', $endtime - $this->curtime) . 's</b>'; - } - else - { - $error = $this->sql_error(); - $this->sql_report .= '<b style="color: red">FAILED</b> - ' . $this->sql_layer . ' Error ' . $error['code'] . ': ' . htmlspecialchars($error['message']); - } - - $this->sql_report .= '</p><br /><br />'; - - $this->sql_time += $endtime - $this->curtime; - break; - - case 'start': - $this->query_hold = $query; - $this->html_hold = ''; - - $this->_sql_report($mode, $query); - - $this->curtime = explode(' ', microtime()); - $this->curtime = $this->curtime[0] + $this->curtime[1]; - - break; - - case 'add_select_row': - - $html_table = func_get_arg(2); - $row = func_get_arg(3); - - if (!$html_table && sizeof($row)) - { - $html_table = true; - $this->html_hold .= '<table cellspacing="1"><tr>'; - - foreach (array_keys($row) as $val) - { - $this->html_hold .= '<th>' . (($val) ? ucwords(str_replace('_', ' ', $val)) : ' ') . '</th>'; - } - $this->html_hold .= '</tr>'; - } - $this->html_hold .= '<tr>'; - - $class = 'row1'; - foreach (array_values($row) as $val) - { - $class = ($class == 'row1') ? 'row2' : 'row1'; - $this->html_hold .= '<td class="' . $class . '">' . (($val) ? $val : ' ') . '</td>'; - } - $this->html_hold .= '</tr>'; - - return $html_table; - - break; - - case 'fromcache': - - $this->_sql_report($mode, $query); - - break; - - case 'record_fromcache': - - $endtime = func_get_arg(2); - $splittime = func_get_arg(3); - - $time_cache = $endtime - $this->curtime; - $time_db = $splittime - $endtime; - $color = ($time_db > $time_cache) ? 'green' : 'red'; - - $this->sql_report .= '<table cellspacing="1"><thead><tr><th>Query results obtained from the cache</th></tr></thead><tbody><tr>'; - $this->sql_report .= '<td class="row3"><textarea style="font-family:\'Courier New\',monospace;width:99%" rows="5" cols="10">' . preg_replace('/\t(AND|OR)(\W)/', "\$1\$2", htmlspecialchars(preg_replace('/[\s]*[\n\r\t]+[\n\r\s\t]*/', "\n", $query))) . '</textarea></td></tr></tbody></table>'; - $this->sql_report .= '<p style="text-align: center;">'; - $this->sql_report .= 'Before: ' . sprintf('%.5f', $this->curtime - $starttime) . 's | After: ' . sprintf('%.5f', $endtime - $starttime) . 's | Elapsed [cache]: <b style="color: ' . $color . '">' . sprintf('%.5f', ($time_cache)) . 's</b> | Elapsed [db]: <b>' . sprintf('%.5f', $time_db) . 's</b></p><br /><br />'; - - // Pad the start time to not interfere with page timing - $starttime += $time_db; - - break; - - default: - - $this->_sql_report($mode, $query); - - break; - } - - return true; - } - - /** - * Get stored data from SQL cache and fill the relevant cach rowset. - * - * @param string $query The query cached. - * - * @return bool True if the caching was successful, else false - * @access private - */ - private function sql_get_cache($query) - { - if (!phpbb::registered('acm') || !phpbb::$acm->supported('sql')) - { - return false; - } - - // Remove extra spaces and tabs - $var_name = preg_replace('/[\n\r\s\t]+/', ' ', $query); - $var_name = md5($this->sql_layer . '_' . $var_name); - - $data = phpbb::$acm->get_sql($var_name); - - if ($data !== false) - { - $this->query_result = ++$this->cache_index; - $this->cache_rowset[$this->query_result] = $data['rowset']; - - return true; - } - - return false; - } - - /** - * Put query to cache. - * - * @param string $query The query cached. - * @param int $cache_ttl Cache lifetime in seconds. - * - * @return bool True if the caching was successful, else false - * @access private - */ - private function sql_put_cache($query, $cache_ttl) - { - if (!phpbb::registered('acm') || !phpbb::$acm->supported('sql')) - { - return false; - } - - // Prepare the data - $var_name = preg_replace('/[\n\r\s\t]+/', ' ', $query); - $var_name = md5($this->sql_layer . '_' . $var_name); - - $data = array( - 'query' => $query, - 'rowset' => array(), - ); - - while ($row = $this->sql_fetchrow($this->query_result)) - { - $data['rowset'][] = $row; - } - $this->sql_freeresult($this->query_result); - - phpbb::$acm->put_sql($var_name, $data, $cache_ttl); - - $this->query_result = ++$this->cache_index; - $this->cache_rowset[$this->query_result] = $data['rowset']; - @reset($this->cache_rowset[$this->query_result]); - - return true; - } - - /** - * Check if an sql cache exist for a specific query id. - * - * @param int $query_id The query_id to check (int) - * - * @return bool True if an cache entry exists. - * @access private - */ - private function sql_cache_exists($query_id) - { - return is_int($query_id) && isset($this->cache_rowset[$query_id]); - } - - /** - * Fetch row from cache (database). Used in {@link phpbb_dbal::sql_fetchrow() sql_fetchrow()}. - * - * @param int $query_id The query_id to fetch from. - * - * @return array The result row - * @access private - */ - private function sql_cache_fetchrow($query_id) - { - list(, $row) = each($this->cache_rowset[$query_id]); - return ($row !== NULL) ? $row : false; - } - - /** - * Fetch a field from the current row of a cached database result (database). Used in {@link phpbb_dbal::sql_fetchfield() sql_fetchfield()}. - * - * @param int $query_id The query_id to fetch from. - * @param string $field The column name. - * - * @return array The field data - * @access private - */ - private function sql_cache_fetchfield($query_id, $field) - { - $row = current($this->cache_rowset[$query_id]); - return ($row !== false && isset($row[$field])) ? $row[$field] : false; - } - - /** - * Free memory used for a cached database result (database). Used in {@link phpbb_dbal::sql_freeresult() sql_freeresult()}. - * - * @param int $query_id The query_id. - * - * @return bool True on success - * @access private - */ - private function sql_cache_freeresult($query_id) - { - if (!isset($this->cache_rowset[$query_id])) - { - return false; - } - - if (($key = $this->sql_get_result_key($query_id)) !== false) - { - unset($this->open_queries[$key]); - } - - unset($this->cache_rowset[$query_id]); - return true; - } - - /** - * Function for validating SQL values - * - * @param mixed Value. Typecasted to it's type. - * - * @return mixed Typecasted value. - * @access private - */ - private function _sql_validate_value($var) - { - if (is_null($var)) - { - return 'NULL'; - } - else if (is_string($var)) - { - return "'" . $this->sql_escape($var) . "'"; - } - else - { - return (is_bool($var)) ? intval($var) : $var; - } - } - - /** - * Add "one" to query count. - * - * @param bool $cached If true, add one to cached query count. Otherwise to non-cached query count - * @access private - */ - private function sql_add_num_queries($cached = false) - { - $this->num_queries['cached'] += ($cached !== false) ? 1 : 0; - $this->num_queries['normal'] += ($cached !== false) ? 0 : 1; - $this->num_queries['total'] += 1; - } - - /** - * Get SQL result key for storing open connection - * - * @param string $query_result Query result id/resource/object - * - * @return mixed Key usable as array key. False if storing is not possible. - * @access private - */ - private function sql_get_result_key($query_result) - { - $key = $query_result; - - if (is_object($query_result)) - { - $key = false; - } - else if (is_resource($query_result)) - { - $key = (int) $query_result; - } - - return $key; - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/firebird.php b/phpBB/includes/db/firebird.php deleted file mode 100644 index be704ad835..0000000000 --- a/phpBB/includes/db/firebird.php +++ /dev/null @@ -1,453 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* Firebird/Interbase Database Abstraction Layer -* Minimum Requirement: 2.0+ -* @package dbal -*/ -class phpbb_dbal_firebird extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'firebird'; - - /** - * @var array Database type map, column layout information - */ - 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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = str_replace('\\', '/', $database); - - // There are three possibilities to connect to an interbase db - if (!$this->server) - { - $use_database = $this->dbname; - } - else if (strpos($this->server, '//') === 0) - { - $use_database = $this->server . $this->dbname; - } - else - { - $use_database = $this->server . ':' . $this->dbname; - } - - $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); - - if (!$this->db_connect_id) - { - return $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. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - 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) - { - @ibase_service_detach($this->service_handle); - } - - return @ibase_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return true; - break; - - case 'commit': - return @ibase_commit(); - break; - - case 'rollback': - return @ibase_rollback(); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @ibase_affected_rows($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - if (!$this->query_result || !$this->last_query_text) - { - return false; - } - - 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) - { - return false; - } - - foreach (get_object_vars($cur_row) as $key => $value) - { - $row[strtolower($key)] = (is_string($value)) ? trim(str_replace(array("\\0", "\\n"), array("\0", "\n"), $value)) : $value; - } - - return (sizeof($row)) ? $row : false; - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @ibase_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return str_replace(array("'", "\0"), array("''", ''), $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'OCTET_LENGTH(' . $col . ')'; - break; - } - } - - /** - * 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') - { - $stmt = ibase_prepare($this->db_connect_id, "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES (" . substr(str_repeat('?, ', sizeof($data)) ,0, -1) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key) - { - $set[] = "$key = ?"; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= $where; - } - - $stmt = ibase_prepare($this->db_connect_id, $query); - } - - // get the stmt onto the top of the function arguments - array_unshift($data, $stmt); - - call_user_func_array('ibase_execute', $data); - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - return array( - 'message' => @ibase_errmsg(), - 'code' => @ibase_errcode() - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @ibase_query($this->db_connect_id, $query); - while ($void = @ibase_fetch_object($result, IBASE_TEXT)) - { - // Take the time spent on parsing rows into account - } - @ibase_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/mssql.php b/phpBB/includes/db/mssql.php deleted file mode 100644 index d0dcb590fd..0000000000 --- a/phpBB/includes/db/mssql.php +++ /dev/null @@ -1,382 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* MSSQL Database Abstraction Layer -* Minimum Requirement is MSSQL 2000+ -* @package dbal -*/ -class phpbb_dbal_mssql extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'mssql'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => '[int]', - 'BINT' => '[float]', - 'UINT' => '[int]', - 'UINT:' => '[int]', - 'TINT:' => '[int]', - 'USINT' => '[int]', - 'BOOL' => '[int]', - 'VCHAR' => '[varchar] (255)', - 'VCHAR:' => '[varchar] (%d)', - 'CHAR:' => '[char] (%d)', - 'XSTEXT' => '[varchar] (1000)', - 'STEXT' => '[varchar] (3000)', - 'TEXT' => '[varchar] (8000)', - 'MTEXT' => '[text]', - 'XSTEXT_UNI'=> '[varchar] (100)', - 'STEXT_UNI' => '[varchar] (255)', - 'TEXT_UNI' => '[varchar] (4000)', - 'MTEXT_UNI' => '[text]', - 'TIMESTAMP' => '[int]', - 'DECIMAL' => '[float]', - 'DECIMAL:' => '[float]', - 'PDECIMAL' => '[float]', - 'PDECIMAL:' => '[float]', - 'VCHAR_UNI' => '[varchar] (255)', - 'VCHAR_UNI:'=> '[varchar] (%d)', - 'VARBINARY' => '[varchar] (255)', - ); - - /** - * 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 = $user; - $this->dbname = $database; - $this->port = $port; - - $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':'; - $this->server = $server . (($this->port) ? $port_delimiter . $this->port : ''); - - @ini_set('mssql.charset', 'UTF-8'); - @ini_set('mssql.textlimit', 2147483647); - @ini_set('mssql.textsize', 2147483647); - - $this->db_connect_id = ($this->persistency) ? @mssql_pconnect($this->server, $this->user, $password, $new_link) : @mssql_connect($this->server, $this->user, $password, $new_link); - - if (!$this->db_connect_id || !$this->dbname) - { - return $this->sql_error(phpbb::$last_notice['message']); - } - - if (!@mssql_select_db($this->dbname, $this->db_connect_id)) - { - return $this->sql_error(''); - } - - return $this->db_connect_id; - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#mssql_version')) === false) - { - $result_id = @mssql_query("SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition')", $this->db_connect_id); - - $row = false; - if ($result_id) - { - $row = @mssql_fetch_assoc($result_id); - @mssql_free_result($result_id); - } - - $this->sql_server_version = ($row) ? trim(implode(' ', $row)) : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#mssql_version', $this->sql_server_version); - } - } - - if ($raw) - { - return $this->sql_server_version; - } - - return ($this->sql_server_version) ? 'MSSQL<br />' . $this->sql_server_version : 'MSSQL'; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @mssql_query($query, $this->db_connect_id); - } - - /** - * 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) - { - // Since TOP is only returning a set number of rows we won't need it if total is set to 0 (return all rows) - if ($total) - { - // We need to grab the total number of rows + the offset number of rows to get the correct result - if (strpos($query, 'SELECT DISTINCT') === 0) - { - $query = 'SELECT DISTINCT TOP ' . ($total + $offset) . ' ' . substr($query, 15); - } - else - { - $query = 'SELECT TOP ' . ($total + $offset) . ' ' . substr($query, 6); - } - } - - $result = $this->sql_query($query, $cache_ttl); - - // Seek by $offset rows - if ($offset) - { - @mssql_data_seek($result, $offset); - } - - return $result; - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @mssql_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @mssql_query('BEGIN TRANSACTION', $this->db_connect_id); - break; - - case 'commit': - return @mssql_query('COMMIT TRANSACTION', $this->db_connect_id); - break; - - case 'rollback': - return @mssql_query('ROLLBACK TRANSACTION', $this->db_connect_id); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @mssql_rows_affected($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - $result_id = @mssql_query('SELECT SCOPE_IDENTITY()', $this->db_connect_id); - - if ($result_id) - { - if ($row = @mssql_fetch_assoc($result_id)) - { - @mssql_free_result($result_id); - return $row['computed']; - } - @mssql_free_result($result_id); - } - - return false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - $row = @mssql_fetch_assoc($query_id); - - // I hope i am able to remove this later... hopefully only a PHP or MSSQL bug - if ($row) - { - foreach ($row as $key => $value) - { - $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value; - } - } - - return $row; - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @mssql_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return str_replace(array("'", "\0"), array("''", ''), $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'DATALENGTH(' . $col . ')'; - break; - } - } - - /** - * 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 = '') - { - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - $error = array( - 'message' => @mssql_get_last_message(), - 'code' => '' - ); - - // Get error code number - $result_id = @mssql_query('SELECT @@ERROR as code', $this->db_connect_id); - if ($result_id) - { - $row = @mssql_fetch_assoc($result_id); - $error['code'] = $row['code']; - @mssql_free_result($result_id); - } - - // Get full error message if possible - $sql = 'SELECT CAST(description as varchar(255)) as message - FROM master.dbo.sysmessages - WHERE error = ' . $error['code']; - $result_id = @mssql_query($sql); - - if ($result_id) - { - $row = @mssql_fetch_assoc($result_id); - if (!empty($row['message'])) - { - $error['message'] .= '<br />' . $row['message']; - } - @mssql_free_result($result_id); - } - - return $error; - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - $html_table = false; - @mssql_query('SET SHOWPLAN_TEXT ON;', $this->db_connect_id); - if ($result = @mssql_query($query, $this->db_connect_id)) - { - @mssql_next_result($result); - while ($row = @mssql_fetch_row($result)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mssql_query('SET SHOWPLAN_TEXT OFF;', $this->db_connect_id); - @mssql_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @mssql_query($query, $this->db_connect_id); - while ($void = @mssql_fetch_assoc($result)) - { - // Take the time spent on parsing rows into account - } - @mssql_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/mssql_2005.php b/phpBB/includes/db/mssql_2005.php deleted file mode 100644 index 4206e1f7e3..0000000000 --- a/phpBB/includes/db/mssql_2005.php +++ /dev/null @@ -1,350 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -include_once(PHPBB_ROOT_PATH . 'includes/db/dbal.' . PHP_EXT); - -/** -* MSSQL Database Abstraction Layer -* Minimum Requirement is MSSQL 2005+ -* @package dbal -*/ -class phpbb_dbal_mssql_2005 extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'mssql'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => '[int]', - 'BINT' => '[float]', - 'UINT' => '[int]', - 'UINT:' => '[int]', - 'TINT:' => '[int]', - 'USINT' => '[int]', - 'BOOL' => '[int]', - 'VCHAR' => '[varchar] (255)', - 'VCHAR:' => '[varchar] (%d)', - 'CHAR:' => '[char] (%d)', - 'XSTEXT' => '[varchar] (1000)', - 'STEXT' => '[varchar] (3000)', - 'TEXT' => '[varchar] (8000)', - 'MTEXT' => '[text]', - 'XSTEXT_UNI'=> '[varchar] (100)', - 'STEXT_UNI' => '[varchar] (255)', - 'TEXT_UNI' => '[varchar] (4000)', - 'MTEXT_UNI' => '[text]', - 'TIMESTAMP' => '[int]', - 'DECIMAL' => '[float]', - 'DECIMAL:' => '[float]', - 'PDECIMAL' => '[float]', - 'PDECIMAL:' => '[float]', - 'VCHAR_UNI' => '[varchar] (255)', - 'VCHAR_UNI:'=> '[varchar] (%d)', - 'VARBINARY' => '[varchar] (255)', - ); - - /** - * 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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = $database; - $this->port = $port; - - $conn_info = array(); - if ($this->user) - { - $conn_info['UID'] = $this->user; - } - - if ($password) - { - $conn_info['PWD'] = $password; - } - - $this->db_connect_id = @sqlsrv_connect($this->server, $conn_info); - - if (!$this->db_connect_id || !$this->dbname) - { - return $this->sql_error(''); - } - - if (!@sqlsrv_query($this->db_connect_id, 'USE ' . $this->dbname)) - { - return $this->sql_error(''); - } - - return $this->db_connect_id; - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#mssql2005_version')) === false) - { - $server_info = @sqlsrv_server_info($this->db_connect_id); - - $this->sql_server_version = (!empty($server_info['SQLServerVersion'])) ? $server_info['SQLServerVersion'] : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#mssql2005_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'MSSQL ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - if (strpos($query, 'BEGIN') === 0 || strpos($query, 'COMMIT') === 0) - { - return true; - } - - return @sqlsrv_query($this->db_connect_id, $query); - } - - /** - * 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) - { - // Since TOP is only returning a set number of rows we won't need it if total is set to 0 (return all rows) - if ($total) - { - // We need to grab the total number of rows + the offset number of rows to get the correct result - if (strpos($query, 'SELECT DISTINCT') === 0) - { - $query = 'SELECT DISTINCT TOP ' . ($total + $offset) . ' ' . substr($query, 15); - } - else - { - $query = 'SELECT TOP ' . ($total + $offset) . ' ' . substr($query, 6); - } - } - - $result = $this->sql_query($query, $cache_ttl); - - // Seek by $offset rows - if ($offset) - { - // We do not fetch the row for rownum == 0 because then the next resultset would be the second row - for ($i = 0; $i < $offset; $i++) - { - if (!$this->sql_fetchrow($result)) - { - return false; - } - } - } - - return $result; - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @sqlsrv_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @sqlsrv_query($this->db_connect_id, 'BEGIN TRANSACTION'); - break; - - case 'commit': - return @sqlsrv_query($this->db_connect_id, 'COMMIT TRANSACTION'); - break; - - case 'rollback': - return @sqlsrv_query($this->db_connect_id, 'ROLLBACK TRANSACTION'); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @sqlsrv_rows_affected($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - $result_id = @sqlsrv_query($this->db_connect_id, 'SELECT SCOPE_IDENTITY()'); - if ($result_id) - { - if ($row = @sqlsrv_fetch_array($result_id, SQLSRV_FETCH_ASSOC)) - { - @sqlsrv_free_stmt($result_id); - return $row['computed']; - } - @sqlsrv_free_stmt($result_id); - } - - return false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - $row = @sqlsrv_fetch_array($query_id, SQLSRV_FETCH_ASSOC); - - // I hope i am able to remove this later... hopefully only a PHP or MSSQL bug - if ($row) - { - foreach ($row as $key => $value) - { - $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value; - } - } - - return $row; - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @sqlsrv_free_stmt($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return str_replace("'", "''", $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'DATALENGTH(' . $col . ')'; - break; - } - } - - /** - * 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 = '') - { - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - $message = $code = array(); - foreach (@sqlsrv_errors() as $error_array) - { - $message[] = $error_array['message']; - $code[] = $error_array['code']; - } - - $error = array( - 'message' => implode('<br />', $message), - 'code' => implode('<br />', $code), - ); - - return $error; - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @sqlsrv_query($this->db_connect_id, $query); - while ($void = @sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) - { - // Take the time spent on parsing rows into account - } - @sqlsrv_free_stmt($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/mssql_odbc.php b/phpBB/includes/db/mssql_odbc.php deleted file mode 100644 index 3fd5635150..0000000000 --- a/phpBB/includes/db/mssql_odbc.php +++ /dev/null @@ -1,380 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -include_once(PHPBB_ROOT_PATH . 'includes/db/dbal.' . PHP_EXT); - -/** -* Unified ODBC functions -* Unified ODBC functions support any database having ODBC driver, for example Adabas D, IBM DB2, iODBC, Solid, Sybase SQL Anywhere... -* Here we only support MSSQL Server 2000+ because of the provided schema -* -* @note number of bytes returned for returning data depends on odbc.defaultlrl php.ini setting. -* If it is limited to 4K for example only 4K of data is returned max, resulting in incomplete theme data for example. -* @note odbc.defaultbinmode may affect UTF8 characters -* -* @package dbal -*/ -class phpbb_dbal_mssql_odbc extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'mssql'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => '[int]', - 'BINT' => '[float]', - 'UINT' => '[int]', - 'UINT:' => '[int]', - 'TINT:' => '[int]', - 'USINT' => '[int]', - 'BOOL' => '[int]', - 'VCHAR' => '[varchar] (255)', - 'VCHAR:' => '[varchar] (%d)', - 'CHAR:' => '[char] (%d)', - 'XSTEXT' => '[varchar] (1000)', - 'STEXT' => '[varchar] (3000)', - 'TEXT' => '[varchar] (8000)', - 'MTEXT' => '[text]', - 'XSTEXT_UNI'=> '[varchar] (100)', - 'STEXT_UNI' => '[varchar] (255)', - 'TEXT_UNI' => '[varchar] (4000)', - 'MTEXT_UNI' => '[text]', - 'TIMESTAMP' => '[int]', - 'DECIMAL' => '[float]', - 'DECIMAL:' => '[float]', - 'PDECIMAL' => '[float]', - 'PDECIMAL:' => '[float]', - 'VCHAR_UNI' => '[varchar] (255)', - 'VCHAR_UNI:'=> '[varchar] (%d)', - 'VARBINARY' => '[varchar] (255)', - ); - - /** - * 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 = $user; - $this->dbname = $database; - $this->port = $port; - - $port_delimiter = (defined('PHP_OS') && substr(PHP_OS, 0, 3) === 'WIN') ? ',' : ':'; - $this->server = $server . (($port) ? $port_delimiter . $port : ''); - - $max_size = @ini_get('odbc.defaultlrl'); - if (!empty($max_size)) - { - $unit = strtolower(substr($max_size, -1, 1)); - $max_size = (int) $max_size; - - if ($unit == 'k') - { - $max_size = floor($max_size / 1024); - } - else if ($unit == 'g') - { - $max_size *= 1024; - } - else if (is_numeric($unit)) - { - $max_size = floor((int) ($max_size . $unit) / 1048576); - } - $max_size = max(8, $max_size) . 'M'; - - @ini_set('odbc.defaultlrl', $max_size); - } - - $this->db_connect_id = ($this->persistency) ? @odbc_pconnect($this->server, $this->user, $password) : @odbc_connect($this->server, $this->user, $password); - - return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#mssqlodbc_version')) === false) - { - $result_id = @odbc_exec($this->db_connect_id, "SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition')"); - - $row = false; - if ($result_id) - { - $row = @odbc_fetch_array($result_id); - @odbc_free_result($result_id); - } - - $this->sql_server_version = ($row) ? trim(implode(' ', $row)) : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#mssqlodbc_version', $this->sql_server_version); - } - } - - if ($raw) - { - return $this->sql_server_version; - } - - return ($this->sql_server_version) ? 'MSSQL (ODBC)<br />' . $this->sql_server_version : 'MSSQL (ODBC)'; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @odbc_exec($this->db_connect_id, $query); - } - - /** - * 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) - { - // Since TOP is only returning a set number of rows we won't need it if total is set to 0 (return all rows) - if ($total) - { - // We need to grab the total number of rows + the offset number of rows to get the correct result - if (strpos($query, 'SELECT DISTINCT') === 0) - { - $query = 'SELECT DISTINCT TOP ' . ($total + $offset) . ' ' . substr($query, 15); - } - else - { - $query = 'SELECT TOP ' . ($total + $offset) . ' ' . substr($query, 6); - } - } - - $result = $this->sql_query($query, $cache_ttl); - - // Seek by $offset rows - if ($offset) - { - // We do not fetch the row for rownum == 0 because then the next resultset would be the second row - for ($i = 0; $i < $offset; $i++) - { - if (!$this->sql_fetchrow($result)) - { - return false; - } - } - } - - return $result; - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @odbc_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @odbc_exec($this->db_connect_id, 'BEGIN TRANSACTION'); - break; - - case 'commit': - return @odbc_exec($this->db_connect_id, 'COMMIT TRANSACTION'); - break; - - case 'rollback': - return @odbc_exec($this->db_connect_id, 'ROLLBACK TRANSACTION'); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @odbc_num_rows($this->query_result) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - $result_id = @odbc_exec($this->db_connect_id, 'SELECT @@IDENTITY'); - - if ($result_id) - { - if (@odbc_fetch_array($result_id)) - { - $id = @odbc_result($result_id, 1); - @odbc_free_result($result_id); - return $id; - } - @odbc_free_result($result_id); - } - - return false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - * @note number of bytes returned depends on odbc.defaultlrl php.ini setting. If it is limited to 4K for example only 4K of data is returned max. - */ - protected function _sql_fetchrow($query_id) - { - return @odbc_fetch_array($query_id); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @odbc_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return str_replace(array("'", "\0"), array("''", ''), $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'DATALENGTH(' . $col . ')'; - break; - } - } - - /** - * 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') - { - $stmt = odbc_prepare($this->db_connect_id, "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES (" . substr(str_repeat('?, ', sizeof($data)) ,0, -1) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key) - { - $set[] = "$key = ?"; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= $where; - } - - $stmt = odbc_prepare($this->db_connect_id, $query); - } - - // get the stmt onto the top of the function arguments - array_unshift($data, $stmt); - - call_user_func_array('odbc_execute', $data); - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - return array( - 'message' => @odbc_errormsg(), - 'code' => @odbc_error() - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @odbc_exec($this->db_connect_id, $query); - while ($void = @odbc_fetch_array($result)) - { - // Take the time spent on parsing rows into account - } - @odbc_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/mysql.php b/phpBB/includes/db/mysql.php deleted file mode 100644 index ac0384d523..0000000000 --- a/phpBB/includes/db/mysql.php +++ /dev/null @@ -1,447 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* MySQL Database Abstraction Layer -* Compatible with: -* MySQL 4.1+ -* MySQL 5.0+ -* @package dbal -*/ -class phpbb_dbal_mysql extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'mysql'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'int(%d)', - 'BINT' => 'bigint(20)', - 'UINT' => 'mediumint(8) UNSIGNED', - 'UINT:' => 'int(%d) UNSIGNED', - 'TINT:' => 'tinyint(%d)', - 'USINT' => 'smallint(4) UNSIGNED', - 'BOOL' => 'tinyint(1) UNSIGNED', - 'VCHAR' => 'varchar(255)', - 'VCHAR:' => 'varchar(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'text', - 'XSTEXT_UNI'=> 'varchar(100)', - 'STEXT' => 'text', - 'STEXT_UNI' => 'varchar(255)', - 'TEXT' => 'text', - 'TEXT_UNI' => 'text', - 'MTEXT' => 'mediumtext', - 'MTEXT_UNI' => 'mediumtext', - 'TIMESTAMP' => 'int(11) UNSIGNED', - 'DECIMAL' => 'decimal(5,2)', - 'DECIMAL:' => 'decimal(%d,2)', - 'PDECIMAL' => 'decimal(6,3)', - 'PDECIMAL:' => 'decimal(%d,3)', - 'VCHAR_UNI' => 'varchar(255)', - 'VCHAR_UNI:'=> 'varchar(%d)', - 'VARBINARY' => 'varbinary(255)', - ); - - /** - * 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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = $database; - $this->port = $port; - - $this->db_connect_id = ($this->persistency) ? @mysql_pconnect($this->server, $this->user, $password, $new_link) : @mysql_connect($this->server, $this->user, $password, $new_link); - - if (!$this->db_connect_id || !$this->dbname) - { - return $this->sql_error(''); - } - - if (!@mysql_select_db($this->dbname, $this->db_connect_id)) - { - return $this->sql_error(''); - } - - @mysql_query("SET NAMES 'utf8'", $this->db_connect_id); - - // enforce strict mode on databases that support it - if (version_compare($this->sql_server_info(true), '5.0.2', '>=')) - { - $result = @mysql_query('SELECT @@session.sql_mode AS sql_mode', $this->db_connect_id); - $row = @mysql_fetch_assoc($result); - @mysql_free_result($result); - - $modes = array_map('trim', explode(',', $row['sql_mode'])); - - // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES - if (!in_array('TRADITIONAL', $modes)) - { - if (!in_array('STRICT_ALL_TABLES', $modes)) - { - $modes[] = 'STRICT_ALL_TABLES'; - } - - if (!in_array('STRICT_TRANS_TABLES', $modes)) - { - $modes[] = 'STRICT_TRANS_TABLES'; - } - } - - $mode = implode(',', $modes); - @mysql_query("SET SESSION sql_mode='{$mode}'", $this->db_connect_id); - } - - return $this->db_connect_id; - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#mysql_version')) === false) - { - $result = @mysql_query('SELECT VERSION() AS version', $this->db_connect_id); - $row = @mysql_fetch_assoc($result); - @mysql_free_result($result); - - $this->sql_server_version = trim($row['version']); - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#mysql_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'MySQL ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @mysql_query($query, $this->db_connect_id); - } - - /** - * 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) - { - // if $total is set to 0 we do not want to limit the number of rows - if ($total == 0) - { - // MySQL 4.1+ no longer supports -1 in limit queries - $total = '18446744073709551615'; - } - - $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @mysql_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @mysql_query('BEGIN', $this->db_connect_id); - break; - - case 'commit': - return @mysql_query('COMMIT', $this->db_connect_id); - break; - - case 'rollback': - return @mysql_query('ROLLBACK', $this->db_connect_id); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @mysql_affected_rows($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - return ($this->db_connect_id) ? @mysql_insert_id($this->db_connect_id) : false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - return @mysql_fetch_assoc($query_id); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @mysql_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - if (!$this->db_connect_id) - { - return @mysql_real_escape_string($msg); - } - - return @mysql_real_escape_string($msg, $this->db_connect_id); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'LENGTH(' . $col . ')'; - break; - } - } - - /** - * 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 = '') - { - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - switch ($stage) - { - case 'FROM': - $data = '(' . $data . ')'; - break; - } - - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - if (!$this->db_connect_id) - { - return array( - 'message' => @mysql_error(), - 'code' => @mysql_errno() - ); - } - - return array( - 'message' => @mysql_error($this->db_connect_id), - 'code' => @mysql_errno($this->db_connect_id) - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - static $test_prof; - static $test_extend; - - // current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING - if ($test_prof === null) - { - $test_prof = $test_extend = false; - if (version_compare($this->sql_server_info(true), '5.0.37', '>=') && version_compare($this->sql_server_info(true), '5.1', '<')) - { - $test_prof = true; - } - - if (version_compare($this->sql_server_info(true), '4.1.1', '>=')) - { - $test_extend = true; - } - } - - switch ($mode) - { - case 'start': - - $explain_query = $query; - if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - - if (preg_match('/^SELECT/', $explain_query)) - { - $html_table = false; - - // begin profiling - if ($test_prof) - { - @mysql_query('SET profiling = 1;', $this->db_connect_id); - } - - if ($result = @mysql_query('EXPLAIN ' . (($test_extend) ? 'EXTENDED ' : '') . "$explain_query", $this->db_connect_id)) - { - while ($row = @mysql_fetch_assoc($result)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysql_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - - if ($test_extend) - { - $html_table = false; - - if ($result = @mysql_query('SHOW WARNINGS', $this->db_connect_id)) - { - $this->html_hold .= '<br />'; - while ($row = @mysql_fetch_assoc($result)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysql_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - } - - if ($test_prof) - { - $html_table = false; - - // get the last profile - if ($result = @mysql_query('SHOW PROFILE ALL;', $this->db_connect_id)) - { - $this->html_hold .= '<br />'; - while ($row = @mysql_fetch_assoc($result)) - { - // make <unknown> HTML safe - if (!empty($row['Source_function'])) - { - $row['Source_function'] = str_replace(array('<', '>'), array('<', '>'), $row['Source_function']); - } - - // remove unsupported features - foreach ($row as $key => $val) - { - if ($val === null) - { - unset($row[$key]); - } - } - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysql_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - - @mysql_query('SET profiling = 0;', $this->db_connect_id); - } - } - - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @mysql_query($query, $this->db_connect_id); - while ($void = @mysql_fetch_assoc($result)) - { - // Take the time spent on parsing rows into account - } - @mysql_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/mysqli.php b/phpBB/includes/db/mysqli.php deleted file mode 100644 index 386efdbff0..0000000000 --- a/phpBB/includes/db/mysqli.php +++ /dev/null @@ -1,472 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* MySQLi Database Abstraction Layer -* Compatible with: -* MySQL 4.1+ -* MySQL 5.0+ -* @package dbal -*/ -class phpbb_dbal_mysqli extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'mysql'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'int(%d)', - 'BINT' => 'bigint(20)', - 'UINT' => 'mediumint(8) UNSIGNED', - 'UINT:' => 'int(%d) UNSIGNED', - 'TINT:' => 'tinyint(%d)', - 'USINT' => 'smallint(4) UNSIGNED', - 'BOOL' => 'tinyint(1) UNSIGNED', - 'VCHAR' => 'varchar(255)', - 'VCHAR:' => 'varchar(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'text', - 'XSTEXT_UNI'=> 'varchar(100)', - 'STEXT' => 'text', - 'STEXT_UNI' => 'varchar(255)', - 'TEXT' => 'text', - 'TEXT_UNI' => 'text', - 'MTEXT' => 'mediumtext', - 'MTEXT_UNI' => 'mediumtext', - 'TIMESTAMP' => 'int(11) UNSIGNED', - 'DECIMAL' => 'decimal(5,2)', - 'DECIMAL:' => 'decimal(%d,2)', - 'PDECIMAL' => 'decimal(6,3)', - 'PDECIMAL:' => 'decimal(%d,3)', - 'VCHAR_UNI' => 'varchar(255)', - 'VCHAR_UNI:'=> 'varchar(%d)', - 'VARBINARY' => 'varbinary(255)', - ); - - /** - * 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 = $user; - $this->server = $server; - $this->dbname = $database; - $this->port = (!$port) ? NULL : $port; - - // Persistant connections not supported by the mysqli extension? - $this->db_connect_id = @mysqli_connect($this->server, $this->user, $password, $this->dbname, $this->port); - - if (!$this->db_connect_id || !$this->dbname) - { - return $this->sql_error(''); - } - - @mysqli_query($this->db_connect_id, "SET NAMES 'utf8'"); - - // enforce strict mode on databases that support it - if (version_compare($this->sql_server_info(true), '5.0.2', '>=')) - { - $result = @mysqli_query($this->db_connect_id, 'SELECT @@session.sql_mode AS sql_mode'); - $row = @mysqli_fetch_assoc($result); - @mysqli_free_result($result); - - $modes = array_map('trim', explode(',', $row['sql_mode'])); - - // TRADITIONAL includes STRICT_ALL_TABLES and STRICT_TRANS_TABLES - if (!in_array('TRADITIONAL', $modes)) - { - if (!in_array('STRICT_ALL_TABLES', $modes)) - { - $modes[] = 'STRICT_ALL_TABLES'; - } - - if (!in_array('STRICT_TRANS_TABLES', $modes)) - { - $modes[] = 'STRICT_TRANS_TABLES'; - } - } - - $mode = implode(',', $modes); - @mysqli_query($this->db_connect_id, "SET SESSION sql_mode='{$mode}'"); - } - - return $this->db_connect_id; - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#mysqli_version')) === false) - { - $result = @mysqli_query($this->db_connect_id, 'SELECT VERSION() AS version'); - $row = @mysqli_fetch_assoc($result); - @mysqli_free_result($result); - - $this->sql_server_version = trim($row['version']); - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#mysqli_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'MySQL(i) ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @mysqli_query($this->db_connect_id, $query); - } - - /** - * 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) - { - // if $total is set to 0 we do not want to limit the number of rows - if ($total == 0) - { - // MySQL 4.1+ no longer supports -1 in limit queries - $total = '18446744073709551615'; - } - - $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @mysqli_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @mysqli_autocommit($this->db_connect_id, false); - break; - - case 'commit': - $result = @mysqli_commit($this->db_connect_id); - @mysqli_autocommit($this->db_connect_id, true); - return $result; - break; - - case 'rollback': - $result = @mysqli_rollback($this->db_connect_id); - @mysqli_autocommit($this->db_connect_id, true); - return $result; - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @mysqli_affected_rows($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - return ($this->db_connect_id) ? @mysqli_insert_id($this->db_connect_id) : false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - return @mysqli_fetch_assoc($query_id); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @mysqli_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return @mysqli_real_escape_string($this->db_connect_id, $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'LENGTH(' . $col . ')'; - break; - } - } - - /** - * 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') - { - $stmt = mysqli_prepare($this->db_connect_id, "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES (" . substr(str_repeat('?, ', sizeof($data)) ,0, -1) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key) - { - $set[] = "$key = ?"; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= ' WHERE ' . $where; - } - - $stmt = mysqli_prepare($this->db_connect_id, $query); - } - - // get the stmt onto the top of the function arguments - array_unshift($data, $stmt); - - call_user_func_array('mysqli_stmt_bind_param', $data); - mysqli_stmt_execute($stmt); - - mysqli_stmt_close($stmt); - } -*/ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - switch ($stage) - { - case 'FROM': - $data = '(' . $data . ')'; - break; - } - - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - if (!$this->db_connect_id) - { - return array( - 'message' => @mysqli_connect_error(), - 'code' => @mysqli_connect_errno() - ); - } - - return array( - 'message' => @mysqli_error($this->db_connect_id), - 'code' => @mysqli_errno($this->db_connect_id) - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - static $test_prof; - static $test_extend; - - // current detection method, might just switch to see the existance of INFORMATION_SCHEMA.PROFILING - if ($test_prof === null) - { - $test_prof = $test_extend = false; - if (version_compare($this->sql_server_info(true), '5.0.37', '>=') && version_compare($this->sql_server_info(true), '5.1', '<')) - { - $test_prof = true; - } - - if (version_compare($this->sql_server_info(true), '4.1.1', '>=')) - { - $test_extend = true; - } - } - - switch ($mode) - { - case 'start': - - $explain_query = $query; - if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - - if (preg_match('/^SELECT/', $explain_query)) - { - $html_table = false; - - // begin profiling - if ($test_prof) - { - @mysqli_query($this->db_connect_id, 'SET profiling = 1;'); - } - - if ($result = @mysqli_query($this->db_connect_id, 'EXPLAIN ' . (($test_extend) ? 'EXTENDED ' : '') . "$explain_query")) - { - while ($row = @mysqli_fetch_assoc($result)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysqli_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - - if ($test_extend) - { - $html_table = false; - - if ($result = @mysqli_query($this->db_connect_id, 'SHOW WARNINGS')) - { - $this->html_hold .= '<br />'; - while ($row = @mysqli_fetch_assoc($result)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysqli_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - } - - if ($test_prof) - { - $html_table = false; - - // get the last profile - if ($result = @mysqli_query($this->db_connect_id, 'SHOW PROFILE ALL;')) - { - $this->html_hold .= '<br />'; - while ($row = @mysqli_fetch_assoc($result)) - { - // make <unknown> HTML safe - if (!empty($row['Source_function'])) - { - $row['Source_function'] = str_replace(array('<', '>'), array('<', '>'), $row['Source_function']); - } - - // remove unsupported features - foreach ($row as $key => $val) - { - if ($val === null) - { - unset($row[$key]); - } - } - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @mysqli_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - - @mysqli_query($this->db_connect_id, 'SET profiling = 0;'); - } - } - - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @mysqli_query($this->db_connect_id, $query); - while ($void = @mysqli_fetch_assoc($result)) - { - // Take the time spent on parsing rows into account - } - @mysqli_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/oracle.php b/phpBB/includes/db/oracle.php deleted file mode 100644 index 3a69565e05..0000000000 --- a/phpBB/includes/db/oracle.php +++ /dev/null @@ -1,664 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* Oracle Database Abstraction Layer -* Minimum Requirement: 9.2+ -* @package dbal -*/ -class phpbb_dbal_oracle extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'oracle'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'number(%d)', - 'BINT' => 'number(20)', - 'UINT' => 'number(8)', - 'UINT:' => 'number(%d)', - 'TINT:' => 'number(%d)', - 'USINT' => 'number(4)', - 'BOOL' => 'number(1)', - 'VCHAR' => 'varchar2(255)', - 'VCHAR:' => 'varchar2(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'varchar2(1000)', - 'STEXT' => 'varchar2(3000)', - 'TEXT' => 'clob', - 'MTEXT' => 'clob', - 'XSTEXT_UNI'=> 'varchar2(300)', - 'STEXT_UNI' => 'varchar2(765)', - 'TEXT_UNI' => 'clob', - 'MTEXT_UNI' => 'clob', - 'TIMESTAMP' => 'number(11)', - 'DECIMAL' => 'number(5, 2)', - 'DECIMAL:' => 'number(%d, 2)', - 'PDECIMAL' => 'number(6, 3)', - 'PDECIMAL:' => 'number(%d, 3)', - 'VCHAR_UNI' => 'varchar2(255)', - 'VCHAR_UNI:'=> array('varchar2(%d)', 'limit' => array('mult', 3, 765, 'clob')), - 'VARBINARY' => 'raw(255)', - ); - - /** - * @var string Last query executed. We need this for sql_nextid() - */ - var $last_query_text = ''; - - /** - * 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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = $database; - $this->port = $port; - - $connect = $database; - - // support for "easy connect naming" - if ($server !== '' && $server !== '/') - { - if (substr($server, -1, 1) == '/') - { - $server == substr($sqlserver, 0, -1); - } - $connect = $server . (($port) ? ':' . $port : '') . '/' . $database; - } - - $this->db_connect_id = ($new_link) ? @oci_new_connect($this->user, $password, $connect, 'AL32UTF8') : (($this->persistency) ? @oci_pconnect($this->user, $password, $connect, 'AL32UTF8') : @oci_connect($this->user, $password, $connect, 'AL32UTF8')); - - return ($this->db_connect_id) ? $this->db_connect_id : $this->sql_error(''); - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#oracle_version')) === false) - { - $sql = "SELECT value - FROM NLS_DATABASE_PARAMETERS - WHERE PARAMETER = 'NLS_RDBMS_VERSION'"; - $result = @ociparse($this->db_connect_id, $sql); - @ociexecute($result, OCI_DEFAULT); - @ocicommit($this->db_connect_id); - - $row = array(); - @ocifetchinto($result, $row, OCI_ASSOC + OCI_RETURN_NULLS); - @ocifreestatement($result); - - $this->sql_server_version = (isset($row['VALUE'])) ? trim($row['VALUE']) : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#oracle_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : @oci_server_version($this->db_connect_id); - } - - /** - * 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; - - $in_transaction = false; - if (!$this->transaction) - { - $this->sql_transaction('begin'); - } - else - { - $in_transaction = true; - } - - $array = array(); - - // We overcome Oracle's 4000 char limit by binding vars - if (strlen($query) > 4000) - { - if (preg_match('/^(INSERT INTO[^(]++)\\(([^()]+)\\) VALUES[^(]++\\((.*?)\\)$/s', $query, $regs)) - { - if (strlen($regs[3]) > 4000) - { - $cols = explode(', ', $regs[2]); - 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) > 4002) - { - $inserts[$key] = ':' . strtoupper($cols[$key]); - $array[$inserts[$key]] = str_replace("''", "'", substr($value, 1, -1)); - } - } - - $query = $regs[1] . '(' . $regs[2] . ') VALUES (' . implode(', ', $inserts) . ')'; - } - } - else if (preg_match_all('/^(UPDATE [\\w_]++\\s+SET )([\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+)(?:,\\s*[\\w_]++\\s*=\\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]+))*+)\\s+(WHERE.*)$/s', $query, $data, PREG_SET_ORDER)) - { - if (strlen($data[0][2]) > 4000) - { - $update = $data[0][1]; - $where = $data[0][3]; - preg_match_all('/([\\w_]++)\\s*=\\s*(\'(?:[^\']++|\'\')*+\'|[\d-.]++)/', $data[0][2], $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]) > 4002) - { - $cols[] = $value[1] . '=:' . strtoupper($value[1]); - $array[$value[1]] = str_replace("''", "'", substr($value[2], 1, -1)); - } - else - { - $cols[] = $value[1] . '=' . $value[2]; - } - } - - $query = $update . implode(', ', $cols) . ' ' . $where; - unset($cols); - } - } - } - - switch (substr($query, 0, 6)) - { - case 'DELETE': - if (preg_match('/^(DELETE FROM [\w_]++ WHERE)((?:\s*(?:AND|OR)?\s*[\w_]+\s*(?:(?:=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]+)|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))*+)$/', $query, $regs)) - { - $query = $regs[1] . $this->_rewrite_where($regs[2]); - unset($regs); - } - break; - - case 'UPDATE': - if (preg_match('/^(UPDATE [\\w_]++\\s+SET [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++)(?:, [\\w_]+\s*=\s*(?:\'(?:[^\']++|\'\')*+\'|[\d-.]++|:\w++))*+\\s+WHERE)(.*)$/s', $query, $regs)) - { - $query = $regs[1] . $this->_rewrite_where($regs[2]); - unset($regs); - } - break; - - case 'SELECT': - $query = preg_replace_callback('/([\w_.]++)\s*(?:(=|<>)\s*(?>\'(?>[^\']++|\'\')*+\'|[\d-.]++|([\w_.]++))|(?:NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]++,? ?)*+\))/', array($this, '_rewrite_col_compare'), $query); - break; - } - - $result = @oci_parse($this->db_connect_id, $query); - - if (!$result) - { - return false; - } - - foreach ($array as $key => $value) - { - @oci_bind_by_name($result, $key, $array[$key], -1); - } - - $success = @oci_execute($result, OCI_DEFAULT); - - if (!$success) - { - return false; - } - - if (!$in_transaction) - { - $this->sql_transaction('commit'); - } - - 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 * FROM (SELECT /*+ FIRST_ROWS */ rownum AS xrownum, a.* FROM (' . $query . ') a WHERE rownum <= ' . ($offset + $total) . ') WHERE xrownum >= ' . $offset; - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @oci_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return true; - break; - - case 'commit': - return @oci_commit($this->db_connect_id); - break; - - case 'rollback': - return @oci_rollback($this->db_connect_id); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->query_result) ? @oci_num_rows($this->query_result) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - if (!$this->query_result || !$this->last_query_text) - { - return false; - } - - if (preg_match('#^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)#is', $this->last_query_text, $tablename)) - { - $query = 'SELECT ' . $tablename[1] . '_seq.currval FROM DUAL'; - $stmt = @oci_parse($this->db_connect_id, $query); - @oci_execute($stmt, OCI_DEFAULT); - - $temp_array = @oci_fetch_array($stmt, OCI_ASSOC + OCI_RETURN_NULLS); - @oci_free_statement($stmt); - - return (isset($temp_array['CURRVAL'])) ? $temp_array['CURRVAL'] : false; - } - - return false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - $row = @oci_fetch_array($query_id, OCI_ASSOC + OCI_RETURN_NULLS); - - if (!$row) - { - return false; - } - - $result_row = array(); - foreach ($row as $key => $value) - { - // Oracle treats empty strings as null - if (is_null($value)) - { - $value = ''; - } - - // OCI->CLOB? - if (is_object($value)) - { - $value = $value->load(); - } - - $result_row[strtolower($key)] = $value; - } - - return $result_row; - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @oci_free_statement($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression . " ESCAPE '\\'"; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return str_replace(array("'", "\0"), array("''", ''), $msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - return 'LENGTH(' . $col . ')'; - break; - - case 'length_text': - return 'dbms_lob.getlength(' . $col . ')'; - break; - } - } - - /** - * 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') - { - $stmt = oci_parse($this->db_connect_id, "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES (:" . implode(', :', array_keys($data)) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key) - { - $set[] = "$key = :$key"; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= $where; - } - - $stmt = oci_parse($this->db_connect_id, $query); - } - - foreach ($data as $column => $value) - { - oci_bind_by_name($stmt, ":$column", $data[$column], -1); - } - - oci_execute($stmt); - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - $error = @oci_error(); - $error = (empty($error)) ? @oci_error($this->query_result) : $error; - $error = (empty($error)) ? @oci_error($this->db_connect_id) : $error; - - if (empty($error)) - { - $error = array( - 'message' => '', - 'code' => '', - ); - } - - return $error; - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - $html_table = false; - - // Grab a plan table, any will do - $sql = "SELECT table_name - FROM USER_TABLES - WHERE table_name LIKE '%PLAN_TABLE%'"; - $stmt = @oci_parse($this->db_connect_id, $sql); - @oci_execute($stmt); - $result = array(); - - if ($result = @oci_fetch_array($stmt, OCI_ASSOC + OCI_RETURN_NULLS)) - { - $table = $result['TABLE_NAME']; - - // This is the statement_id that will allow us to track the plan - $statement_id = substr(md5($query), 0, 30); - - // Remove any stale plans - $stmt2 = @oci_parse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'"); - @oci_execute($stmt2); - @oci_free_statement($stmt2); - - // Explain the plan - $sql = "EXPLAIN PLAN - SET STATEMENT_ID = '$statement_id' - FOR $query"; - $stmt2 = @ociparse($this->db_connect_id, $sql); - @oci_execute($stmt2); - @oci_free_statement($stmt2); - - // Get the data from the plan - $sql = "SELECT operation, options, object_name, object_type, cardinality, cost - FROM plan_table - START WITH id = 0 AND statement_id = '$statement_id' - CONNECT BY PRIOR id = parent_id - AND statement_id = '$statement_id'"; - $stmt2 = @oci_parse($this->db_connect_id, $sql); - @oci_execute($stmt2); - - $row = array(); - while ($row = @oci_fetch_array($stmt2, OCI_ASSOC + OCI_RETURN_NULLS)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - @oci_free_statement($stmt2); - - // Remove the plan we just made, we delete them on request anyway - $stmt2 = @oci_parse($this->db_connect_id, "DELETE FROM $table WHERE statement_id='$statement_id'"); - @oci_execute($stmt2); - @oci_free_statement($stmt2); - } - - @oci_free_statement($stmt); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @oci_parse($this->db_connect_id, $query); - $success = @oci_execute($result, OCI_DEFAULT); - $row = array(); - - while ($void = @oci_fetch_array($result, OCI_ASSOC + OCI_RETURN_NULLS)) - { - // Take the time spent on parsing rows into account - } - @oci_free_statement($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } - - /** - * Oracle specific code to handle the fact that it does not compare columns properly - * @access private - */ - private function _rewrite_col_compare($args) - { - if (sizeof($args) == 4) - { - if ($args[2] == '=') - { - return '(' . $args[0] . ' OR (' . $args[1] . ' is NULL AND ' . $args[3] . ' is NULL))'; - } - else if ($args[2] == '<>') - { - // really just a fancy way of saying foo <> bar or (foo is NULL XOR bar is NULL) but SQL has no XOR :P - return '(' . $args[0] . ' OR ((' . $args[1] . ' is NULL AND ' . $args[3] . ' is NOT NULL) OR (' . $args[1] . ' is NOT NULL AND ' . $args[3] . ' is NULL)))'; - } - } - else - { - return $this->_rewrite_where($args[0]); - } - } - - /** - * Oracle specific code to handle it's lack of sanity - * @access private - */ - private function _rewrite_where($where_clause) - { - preg_match_all('/\s*(AND|OR)?\s*([\w_.]++)\s*(?:(=|<[=>]?|>=?)\s*((?>\'(?>[^\']++|\'\')*+\'|[\d-.]+))|((NOT )?IN\s*\((?>\'(?>[^\']++|\'\')*+\',? ?|[\d-.]+,? ?)*+\)))/', $where_clause, $result, PREG_SET_ORDER); - $out = ''; - - foreach ($result as $val) - { - if (!isset($val[5])) - { - if ($val[4] !== "''") - { - $out .= $val[0]; - } - else - { - $out .= ' ' . $val[1] . ' ' . $val[2]; - if ($val[3] == '=') - { - $out .= ' is NULL'; - } - else if ($val[3] == '<>') - { - $out .= ' is NOT NULL'; - } - } - } - else - { - $in_clause = array(); - $sub_exp = substr($val[5], strpos($val[5], '(') + 1, -1); - $extra = false; - preg_match_all('/\'(?>[^\']++|\'\')*+\'|[\d-.]++/', $sub_exp, $sub_vals, PREG_PATTERN_ORDER); - $i = 0; - - foreach ($sub_vals[0] as $sub_val) - { - // two things: - // 1) This determines if an empty string was in the IN clausing, making us turn it into a NULL comparison - // 2) This fixes the 1000 list limit that Oracle has (ORA-01795) - if ($sub_val !== "''") - { - $in_clause[(int) $i++/1000][] = $sub_val; - } - else - { - $extra = true; - } - } - - if (!$extra && $i < 1000) - { - $out .= $val[0]; - } - else - { - $out .= ' ' . $val[1] . '('; - $in_array = array(); - - // constuct each IN() clause - foreach ($in_clause as $in_values) - { - $in_array[] = $val[2] . ' ' . (isset($val[6]) ? $val[6] : '') . 'IN(' . implode(', ', $in_values) . ')'; - } - - // Join the IN() clauses against a few ORs (IN is just a nicer OR anyway) - $out .= implode(' OR ', $in_array); - - // handle the empty string case - if ($extra) - { - $out .= ' OR ' . $val[2] . ' is ' . (isset($val[6]) ? $val[6] : '') . 'NULL'; - } - $out .= ')'; - - unset($in_array, $in_clause); - } - } - } - - return $out; - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/postgres.php b/phpBB/includes/db/postgres.php deleted file mode 100644 index d74a8167e9..0000000000 --- a/phpBB/includes/db/postgres.php +++ /dev/null @@ -1,409 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* PostgreSQL Database Abstraction Layer -* Minimum Requirement: 8.2+ -* @package dbal -*/ -class phpbb_dbal_postgres extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'postgres'; - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'INT4', - 'BINT' => 'INT8', - 'UINT' => 'INT4', // unsigned - 'UINT:' => 'INT4', // unsigned - 'USINT' => 'INT2', // unsigned - 'BOOL' => 'INT2', // unsigned - 'TINT:' => 'INT2', - 'VCHAR' => 'varchar(255)', - 'VCHAR:' => 'varchar(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'varchar(1000)', - 'STEXT' => 'varchar(3000)', - 'TEXT' => 'varchar(8000)', - 'MTEXT' => 'TEXT', - 'XSTEXT_UNI'=> 'varchar(100)', - 'STEXT_UNI' => 'varchar(255)', - 'TEXT_UNI' => 'varchar(4000)', - 'MTEXT_UNI' => 'TEXT', - 'TIMESTAMP' => 'INT4', // unsigned - 'DECIMAL' => 'decimal(5,2)', - 'DECIMAL:' => 'decimal(%d,2)', - 'PDECIMAL' => 'decimal(6,3)', - 'PDECIMAL:' => 'decimal(%d,3)', - 'VCHAR_UNI' => 'varchar(255)', - 'VCHAR_UNI:'=> 'varchar(%d)', - 'VARBINARY' => 'bytea', - ); - - /** - * @var string PostgreSQL schema (if supplied with $database -> database.schema) - */ - public $schema = ''; - - /** - * 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 = $user; - $this->server = $server; - $this->dbname = $database; - $this->port = $port; - - $connect_string = ''; - - if ($this->user) - { - $connect_string .= 'user=' . $this->user . ' '; - } - - if ($password) - { - $connect_string .= 'password=' . $password . ' '; - } - - if ($this->server) - { - if (strpos($this->server, ':') !== false) - { - list($this->server, $this->port) = explode(':', $this->server, 2); - } - - if ($this->server !== 'localhost') - { - $connect_string .= 'host=' . $this->server . ' '; - } - - if ($this->port) - { - $connect_string .= 'port=' . $this->port . ' '; - } - } - - $this->schema = ''; - - if ($this->dbname) - { - if (strpos($this->dbname, '.') !== false) - { - list($this->dbname, $this->schema) = explode('.', $this->dbname, 2); - } - $connect_string .= 'dbname=' . $this->dbname; - } - - $this->db_connect_id = ($this->persistency) ? @pg_pconnect($connect_string, ($new_link) ? PGSQL_CONNECT_FORCE_NEW : false) : @pg_connect($connect_string, ($new_link) ? PGSQL_CONNECT_FORCE_NEW : false); - - if (!$this->db_connect_id) - { - return $this->sql_error(htmlspecialchars_decode(phpbb::$last_notice['message'])); - } - - if ($this->schema) - { - @pg_query($this->db_connect_id, 'SET search_path TO ' . $this->schema); - } - - return $this->db_connect_id; - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#pgsql_version')) === false) - { - $query_id = @pg_query($this->db_connect_id, 'SELECT VERSION() AS version'); - $row = @pg_fetch_assoc($query_id, null); - @pg_free_result($query_id); - - $this->sql_server_version = (!empty($row['version'])) ? trim(substr($row['version'], 10)) : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#pgsql_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'PostgreSQL ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @pg_query($this->db_connect_id, $query); - } - - /** - * 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) - { - // if $total is set to 0 we do not want to limit the number of rows - if ($total == 0) - { - $total = 'ALL'; - } - - $query .= "\n LIMIT $total OFFSET $offset"; - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @pg_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @pg_query($this->db_connect_id, 'BEGIN'); - break; - - case 'commit': - return @pg_query($this->db_connect_id, 'COMMIT'); - break; - - case 'rollback': - return @pg_query($this->db_connect_id, 'ROLLBACK'); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->query_result) ? @pg_affected_rows($this->query_result) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - if (!$this->db_connect_id) - { - return false; - } - - $query = "SELECT lastval() AS last_value"; - $temp_q_id = @pg_query($this->db_connect_id, $query); - - if (!$temp_q_id) - { - return false; - } - - $temp_result = @pg_fetch_assoc($temp_q_id, NULL); - @pg_free_result($query_id); - - return ($temp_result) ? $temp_result['last_value'] : false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - return @pg_fetch_assoc($query_id, null); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return @pg_free_result($query_id); - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - return $expression; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - * Note: Do not use for bytea values if we may use them at a later stage - */ - public function sql_escape($msg) - { - return @pg_escape_string($msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'LENGTH(' . $col . ')'; - break; - } - } - -/* - /** - * 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 = '') - { - // for now, stmtname is an empty string, it might change to something more unique in the future - if ($type === 'INSERT') - { - $stmt = pg_prepare($this->dbms_type, '', "INSERT INTO $table (". implode(', ', array_keys($data)) . ") VALUES ($" . implode(', $', range(1, sizeof($data))) . ')'); - } - else - { - $query = "UPDATE $table SET "; - - $set = array(); - foreach (array_keys($data) as $key_id => $key) - { - $set[] = $key . ' = $' . $key_id; - } - $query .= implode(', ', $set); - - if ($where !== '') - { - $query .= $where; - } - - $stmt = pg_prepare($this->db_connect_id, '', $query); - } - - // add the stmtname to the top - array_unshift($data, ''); - - // add the connection resource - array_unshift($data, $this->db_connect_id); - - call_user_func_array('pg_execute', $data); - } -*/ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - return array( - 'message' => (!$this->db_connect_id) ? @pg_last_error() : @pg_last_error($this->db_connect_id), - 'code' => '' - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - - $explain_query = $query; - if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m)) - { - $explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2]; - } - - if (preg_match('/^SELECT/', $explain_query)) - { - $html_table = false; - - if ($result = @pg_query($this->db_connect_id, "EXPLAIN $explain_query")) - { - while ($row = @pg_fetch_assoc($result, NULL)) - { - $html_table = $this->sql_report('add_select_row', $query, $html_table, $row); - } - } - @pg_free_result($result); - - if ($html_table) - { - $this->html_hold .= '</table>'; - } - } - - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @pg_query($this->db_connect_id, $query); - while ($void = @pg_fetch_assoc($result, NULL)) - { - // Take the time spent on parsing rows into account - } - @pg_free_result($result); - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file diff --git a/phpBB/includes/db/sqlite.php b/phpBB/includes/db/sqlite.php deleted file mode 100644 index 0c5cd74f12..0000000000 --- a/phpBB/includes/db/sqlite.php +++ /dev/null @@ -1,307 +0,0 @@ -<?php -/** -* -* @package dbal -* @version $Id$ -* @copyright (c) 2005 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -/** -* @ignore -*/ -if (!defined('IN_PHPBB')) -{ - exit; -} - -/** -* Sqlite Database Abstraction Layer -* Minimum Requirement: 2.8.2+ -* @package dbal -*/ -class phpbb_dbal_sqlite extends phpbb_dbal -{ - /** - * @var string Database type. No distinction between versions or used extensions. - */ - public $dbms_type = 'sqlite'; - - /** - * Database features - * - * <ul> - * <li>multi_insert: Supports multi inserts</li> - * <li>count_distinct: Supports COUNT(DISTINGT ...)</li> - * <li>multi_table_deletion: Supports multiple table deletion</li> - * <li>truncate: Supports table truncation</li> - * </ul> - * - * @var array - */ - public $features = array( - 'multi_insert' => true, - // like MS ACCESS, SQLite does not support COUNT(DISTINCT ...) - 'count_distinct' => false, - 'multi_table_deletion' => true, - // can't truncate a table - 'truncate' => false, - ); - - /** - * @var array Database type map, column layout information - */ - public $dbms_type_map = array( - 'INT:' => 'int(%d)', - 'BINT' => 'bigint(20)', - 'UINT' => 'INTEGER UNSIGNED', //'mediumint(8) UNSIGNED', - 'UINT:' => 'INTEGER UNSIGNED', // 'int(%d) UNSIGNED', - 'TINT:' => 'tinyint(%d)', - 'USINT' => 'INTEGER UNSIGNED', //'mediumint(4) UNSIGNED', - 'BOOL' => 'INTEGER UNSIGNED', //'tinyint(1) UNSIGNED', - 'VCHAR' => 'varchar(255)', - 'VCHAR:' => 'varchar(%d)', - 'CHAR:' => 'char(%d)', - 'XSTEXT' => 'text(65535)', - 'STEXT' => 'text(65535)', - 'TEXT' => 'text(65535)', - 'MTEXT' => 'mediumtext(16777215)', - 'XSTEXT_UNI'=> 'text(65535)', - 'STEXT_UNI' => 'text(65535)', - 'TEXT_UNI' => 'text(65535)', - 'MTEXT_UNI' => 'mediumtext(16777215)', - 'TIMESTAMP' => 'INTEGER UNSIGNED', //'int(11) UNSIGNED', - 'DECIMAL' => 'decimal(5,2)', - 'DECIMAL:' => 'decimal(%d,2)', - 'PDECIMAL' => 'decimal(6,3)', - 'PDECIMAL:' => 'decimal(%d,3)', - 'VCHAR_UNI' => 'varchar(255)', - 'VCHAR_UNI:'=> 'varchar(%d)', - 'VARBINARY' => 'blob', - ); - - /** - * 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 = $user; - $this->server = $server . (($port) ? ':' . $port : ''); - $this->dbname = $database; - - $error = ''; - $this->db_connect_id = ($this->persistency) ? @sqlite_popen($this->server, 0666, $error) : @sqlite_open($this->server, 0666, $error); - - if ($this->db_connect_id) - { - @sqlite_query('PRAGMA short_column_names = 1', $this->db_connect_id); - @sqlite_query('PRAGMA encoding = "UTF-8"', $this->db_connect_id); - } - - return ($this->db_connect_id) ? true : array('message' => $error); - } - - /** - * Version information about used database. See {@link phpbb_dbal::sql_server_info() sql_server_info()} for details. - */ - public function sql_server_info($raw = false) - { - if (!phpbb::registered('acm') || ($this->sql_server_version = phpbb::$acm->get('#sqlite_version')) === false) - { - $result = @sqlite_query('SELECT sqlite_version() AS version', $this->db_connect_id); - $row = @sqlite_fetch_array($result, SQLITE_ASSOC); - - $this->sql_server_version = (!empty($row['version'])) ? $row['version'] : 0; - - if (phpbb::registered('acm')) - { - phpbb::$acm->put('#sqlite_version', $this->sql_server_version); - } - } - - return ($raw) ? $this->sql_server_version : 'SQLite ' . $this->sql_server_version; - } - - /** - * DB-specific base query method. See {@link phpbb_dbal::_sql_query() _sql_query()} for details. - */ - protected function _sql_query($query) - { - return @sqlite_query($query, $this->db_connect_id); - } - - /** - * 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) - { - // if $total is set to 0 we do not want to limit the number of rows - if ($total == 0) - { - $total = -1; - } - - $query .= "\n LIMIT " . ((!empty($offset)) ? $offset . ', ' . $total : $total); - - return $this->sql_query($query, $cache_ttl); - } - - /** - * Close sql connection. See {@link phpbb_dbal::_sql_close() _sql_close()} for details. - */ - protected function _sql_close() - { - return @sqlite_close($this->db_connect_id); - } - - /** - * SQL Transaction. See {@link phpbb_dbal::_sql_transaction() _sql_transaction()} for details. - */ - protected function _sql_transaction($status) - { - switch ($status) - { - case 'begin': - return @sqlite_query('BEGIN', $this->db_connect_id); - break; - - case 'commit': - return @sqlite_query('COMMIT', $this->db_connect_id); - break; - - case 'rollback': - return @sqlite_query('ROLLBACK', $this->db_connect_id); - break; - } - - return true; - } - - /** - * Return number of affected rows. See {@link phpbb_dbal::sql_affectedrows() sql_affectedrows()} for details. - */ - public function sql_affectedrows() - { - return ($this->db_connect_id) ? @sqlite_changes($this->db_connect_id) : false; - } - - /** - * Get last inserted id after insert statement. See {@link phpbb_dbal::sql_nextid() sql_nextid()} for details. - */ - public function sql_nextid() - { - return ($this->db_connect_id) ? @sqlite_last_insert_rowid($this->db_connect_id) : false; - } - - /** - * Fetch current row. See {@link phpbb_dbal::_sql_fetchrow() _sql_fetchrow()} for details. - */ - protected function _sql_fetchrow($query_id) - { - return @sqlite_fetch_array($query_id, SQLITE_ASSOC); - } - - /** - * Free query result. See {@link phpbb_dbal::_sql_freeresult() _sql_freeresult()} for details. - */ - protected function _sql_freeresult($query_id) - { - return true; - } - - /** - * Correctly adjust LIKE expression for special characters. See {@link phpbb_dbal::_sql_like_expression() _sql_like_expression()} for details. - */ - protected function _sql_like_expression($expression) - { - // Unlike LIKE, GLOB is case sensitive (unfortunatly). SQLite users need to live with it! - // We only catch * and ? here, not the character map possible for file globbing. - $expression = str_replace(array(chr(0) . '_', chr(0) . '%'), array(chr(0) . '?', chr(0) . '*'), $expression); - - $expression = str_replace(array('?', '*'), array("\?", "\*"), $expression); - $expression = str_replace(array(chr(0) . "\?", chr(0) . "\*"), array('?', '*'), $expression); - - return 'GLOB \'' . $this->sql_escape($expression) . '\''; - } - - /** - * Escape string used in sql query. See {@link phpbb_dbal::sql_escape() sql_escape()} for details. - */ - public function sql_escape($msg) - { - return @sqlite_escape_string($msg); - } - - /** - * Expose a DBMS specific function. See {@link phpbb_dbal::sql_function() sql_function()} for details. - */ - public function sql_function($type, $col) - { - switch ($type) - { - case 'length_varchar': - case 'length_text': - return 'LENGTH(' . $col . ')'; - break; - } - } - - /** - * 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 = '') - { - } - */ - - /** - * Build DB-specific query bits. See {@link phpbb_dbal::_sql_custom_build() _sql_custom_build()} for details. - */ - protected function _sql_custom_build($stage, $data) - { - return $data; - } - - /** - * return sql error array. See {@link phpbb_dbal::_sql_error() _sql_error()} for details. - */ - protected function _sql_error() - { - return array( - 'message' => @sqlite_error_string(@sqlite_last_error($this->db_connect_id)), - 'code' => @sqlite_last_error($this->db_connect_id) - ); - } - - /** - * 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. - */ - protected function _sql_report($mode, $query = '') - { - switch ($mode) - { - case 'start': - break; - - case 'fromcache': - $endtime = explode(' ', microtime()); - $endtime = $endtime[0] + $endtime[1]; - - $result = @sqlite_query($query, $this->db_connect_id); - while ($void = @sqlite_fetch_array($result, SQLITE_ASSOC)) - { - // Take the time spent on parsing rows into account - } - - $splittime = explode(' ', microtime()); - $splittime = $splittime[0] + $splittime[1]; - - $this->sql_report('record_fromcache', $query, $endtime, $splittime); - - break; - } - } -} - -?>
\ No newline at end of file |