=== modified file 'includes/bootstrap.inc' --- includes/bootstrap.inc 2009-10-09 16:33:13 +0000 +++ includes/bootstrap.inc 2009-10-12 22:12:18 +0000 @@ -569,6 +569,41 @@ function drupal_settings_initialize() { } $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS'; session_name($prefix . md5($session_name)); + + // Use the simpletest database prefix passed by the user agent header. + if (preg_match("/^simpletest\d+$/", $_SERVER['HTTP_USER_AGENT'])) { + // Set the test run id for use in other parts of Drupal. + drupal_test_info(array('test_run_id' => $_SERVER['HTTP_USER_AGENT'], 'in_child_site' => TRUE)); + + foreach ($databases['default'] as $target => $value) { + // Extract the current default database prefix. + if (empty($value['prefix'])) { + $current_prefix = ''; + } + else if (is_array($value['prefix'])) { + $current_prefix = $value['prefix']['default']; + } + else { + $current_prefix = $value['prefix']; + } + + // Remove the current database prefix and replace it by our own. + $databases['default'][$target]['prefix'] = array( + 'default' => $current_prefix . $_SERVER['HTTP_USER_AGENT'], + ); + } + } +} + +/** + * Retrieve (and optionally set) information about the current test being run. + */ +function drupal_test_info($value = FALSE) { + static $cache; + if ($value !== FALSE) { + $cache = $value; + } + return $cache; } /** === modified file 'includes/common.inc' --- includes/common.inc 2009-10-11 06:05:53 +0000 +++ includes/common.inc 2009-10-12 21:43:21 +0000 @@ -792,8 +792,6 @@ function drupal_access_denied() { * A string containing the response body that was received. */ function drupal_http_request($url, array $options = array()) { - global $db_prefix; - $result = new stdClass(); // Parse the URL and make sure we can handle the schema. @@ -892,8 +890,8 @@ function drupal_http_request($url, array // user-agent is used to ensure that multiple testing sessions running at the // same time won't interfere with each other as they would if the database // prefix were stored statically in a file or database variable. - if (is_string($db_prefix) && preg_match("/simpletest\d+/", $db_prefix, $matches)) { - $options['headers']['User-Agent'] = drupal_generate_test_ua($matches[0]); + if ($test_info = drupal_test_info()) { + $options['headers']['User-Agent'] = $test_info['test_run_id']; } $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n"; === modified file 'includes/database/database.inc' --- includes/database/database.inc 2009-10-12 02:00:04 +0000 +++ includes/database/database.inc 2009-10-12 21:44:35 +0000 @@ -317,6 +317,22 @@ abstract class DatabaseConnection extend */ protected $schema = NULL; + /** + * The default prefix used by this database connection. + * + * Separated from the other prefixes for performance reasons. + * + * @var string + */ + protected $defaultPrefix = ''; + + /** + * The non-default prefixes used by this database connection. + * + * @var array + */ + protected $prefixes = array(); + function __construct($dsn, $username, $password, $driver_options = array()) { // Because the other methods don't seem to work right. $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; @@ -390,6 +406,24 @@ abstract class DatabaseConnection extend } /** + * Preprocess the prefix used by this database connection. + * + * @param $prefix + * The prefix, in any of the multiple forms documented in default.settings.php. + */ + protected function setPrefix($prefix) { + if (is_array($prefix)) { + $this->defaultPrefix = isset($prefix['default']) ? $prefix['default'] : ''; + unset($prefix['default']); + $this->prefixes = $prefix; + } + else { + $this->defaultPrefix = $prefix; + $this->prefixes = array(); + } + } + + /** * Append a database prefix to all tables in a query. * * Queries sent to Drupal should wrap all table names in curly brackets. This @@ -403,27 +437,12 @@ abstract class DatabaseConnection extend * The properly-prefixed string. */ public function prefixTables($sql) { - global $db_prefix; - - if (is_array($db_prefix)) { - if (array_key_exists('default', $db_prefix)) { - $tmp = $db_prefix; - unset($tmp['default']); - foreach ($tmp as $key => $val) { - $sql = strtr($sql, array('{' . $key . '}' => $val . $key)); - } - return strtr($sql, array('{' => $db_prefix['default'] , '}' => '')); - } - else { - foreach ($db_prefix as $key => $val) { - $sql = strtr($sql, array('{' . $key . '}' => $val . $key)); - } - return strtr($sql, array('{' => '' , '}' => '')); - } - } - else { - return strtr($sql, array('{' => $db_prefix , '}' => '')); + // Replace specific table prefixes first. + foreach ($this->prefixes as $key => $val) { + $sql = strtr($sql, array('{' . $key . '}' => $val . $key)); } + // Then replace remaining tables with the default prefix. + return strtr($sql, array('{' => $this->defaultPrefix , '}' => '')); } /** @@ -1260,6 +1279,20 @@ abstract class Database { if (empty($value['driver'])) { $databaseInfo[$index][$target] = $databaseInfo[$index][$target][mt_rand(0, count($databaseInfo[$index][$target]) - 1)]; } + + // Parse the prefix information. + if (!isset($databaseInfo[$index][$target]['prefix'])) { + // Default to an empty prefix. + $databaseInfo[$index][$target]['prefix'] = array( + 'default' => '', + ); + } + else if (!is_array($databaseInfo[$index][$target]['prefix'])) { + // Transform the flat form into an array form. + $databaseInfo[$index][$target]['prefix'] = array( + 'default' => $databaseInfo[$index][$target]['prefix'], + ); + } } } @@ -1319,7 +1352,40 @@ abstract class Database { if (!empty(self::$databaseInfo[$key])) { return self::$databaseInfo[$key]; } + } + + /** + * Rename a connection and its corresponding connection information. + * + * @param $old_key + * The old connection key. + * @param $new_key + * The new connection key. + */ + final public static function renameConnection($old_key, $new_key) { + if (empty(self::$databaseInfo)) { + self::parseConnectionInfo(); + } + + if (!empty(self::$databaseInfo[$old_key]) && empty(self::$databaseInfo[$new_key])) { + self::$databaseInfo[$new_key] = self::$databaseInfo[$old_key]; + unset(self::$databaseInfo[$old_key]); + if (isset(self::$connections[$old_key])) { + self::$connections[$new_key] = self::$connections[$old_key]; + unset(self::$connections[$old_key]); + } + } + } + /** + * Remove a connection and its corresponding connection information. + * + * @param $key + * The connection key. + */ + final public static function removeConnection($key) { + unset(self::$databaseInfo[$key]); + unset(self::$connections[$key]); } /** @@ -1332,7 +1398,6 @@ abstract class Database { * The database target to open. */ final protected static function openConnection($key, $target) { - global $db_prefix; if (empty(self::$databaseInfo)) { self::parseConnectionInfo(); @@ -1359,13 +1424,6 @@ abstract class Database { if (!empty(self::$logs[$key])) { $new_connection->setLogger(self::$logs[$key]); } - - // We need to pass around the simpletest database prefix in the request - // and we put that in the user_agent header. The header HMAC was already - // validated in bootstrap.inc. - if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);/", $_SERVER['HTTP_USER_AGENT'], $matches)) { - $db_prefix .= $matches[1]; - } return $new_connection; } catch (Exception $e) { === modified file 'includes/database/mysql/database.inc' --- includes/database/mysql/database.inc 2009-09-18 00:04:21 +0000 +++ includes/database/mysql/database.inc 2009-10-12 21:34:26 +0000 @@ -25,6 +25,8 @@ class DatabaseConnection_mysql extends D $connection_options['port'] = 3306; } + $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : ''); + $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . $connection_options['port'] . ';dbname=' . $connection_options['database']; parent::__construct($dsn, $connection_options['username'], $connection_options['password'], array( // So we don't have to mess around with cursors and unbuffered queries by default. === modified file 'includes/database/pgsql/database.inc' --- includes/database/pgsql/database.inc 2009-09-18 00:04:21 +0000 +++ includes/database/pgsql/database.inc 2009-10-12 21:45:24 +0000 @@ -26,6 +26,8 @@ class DatabaseConnection_pgsql extends D $connection_options['port'] = 5432; } + $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : ''); + // PostgreSQL in trust mode doesn't require a password to be supplied. if (empty($connection_options['password'])) { $connection_options['password'] = null; === modified file 'includes/database/sqlite/database.inc' --- includes/database/sqlite/database.inc 2009-09-18 00:04:21 +0000 +++ includes/database/sqlite/database.inc 2009-10-12 21:45:48 +0000 @@ -25,6 +25,8 @@ class DatabaseConnection_sqlite extends // This driver defaults to transaction support, except if explicitly passed FALSE. $this->transactionSupport = !isset($connection_options['transactions']) || $connection_options['transactions'] !== FALSE; + $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : ''); + parent::__construct('sqlite:' . $connection_options['database'], '', '', array( // Force column names to lower case. PDO::ATTR_CASE => PDO::CASE_LOWER, === modified file 'install.php' --- install.php 2009-10-12 02:00:04 +0000 +++ install.php 2009-10-12 21:51:16 +0000 @@ -776,7 +776,7 @@ function install_verify_completed_task() * Verify existing settings.php */ function install_verify_settings() { - global $db_prefix, $databases; + global $databases; // Verify existing settings (if any). if (!empty($databases)) { @@ -802,7 +802,7 @@ function install_verify_settings() { * The form API definition for the database configuration form. */ function install_settings_form($form, &$form_state, &$install_state) { - global $databases, $db_prefix; + global $databases; $profile = $install_state['parameters']['profile']; $install_locale = $install_state['parameters']['locale']; @@ -897,13 +897,13 @@ function install_settings_form($form, &$ ); // Table prefix - $db_prefix = ($profile == 'default') ? 'drupal_' : $profile . '_'; - $form['advanced_options']['db_prefix'] = array( + $prefix = ($profile == 'default') ? 'drupal_' : $profile . '_'; + $form['advanced_options']['prefix'] = array( '#type' => 'textfield', '#title' => st('Table prefix'), '#default_value' => '', '#size' => 45, - '#description' => st('If more than one application will be sharing this database, enter a table prefix such as %prefix for your @drupal site here.', array('@drupal' => drupal_install_profile_name(), '%prefix' => $db_prefix)), + '#description' => st('If more than one application will be sharing this database, enter a table prefix such as %prefix for your @drupal site here.', array('@drupal' => drupal_install_profile_name(), '%prefix' => $prefix)), ); $form['save'] = array( @@ -936,12 +936,12 @@ function install_database_errors($databa global $databases; $errors = array(); // Verify the table prefix - if (!empty($database['db_prefix']) && is_string($database['db_prefix']) && !preg_match('/^[A-Za-z0-9_.]+$/', $database['db_prefix'])) { - $errors['db_prefix'] = st('The database table prefix you have entered, %db_prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%db_prefix' => $database['db_prefix'])); + if (!empty($database['prefix']) && is_string($database['prefix']) && !preg_match('/^[A-Za-z0-9_.]+$/', $database['prefix'])) { + $errors['prefix'] = st('The database table prefix you have entered, %prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%prefix' => $database['prefix'])); } if (!empty($database['port']) && !is_numeric($database['port'])) { - $errors['db_port'] = st('Database port must be a number.'); + $errors['port'] = st('Database port must be a number.'); } // Check database type @@ -977,16 +977,12 @@ function install_database_errors($databa function install_settings_form_submit($form, &$form_state) { global $install_state; - $database = array_intersect_key($form_state['values']['_database'], array_flip(array('driver', 'database', 'username', 'password', 'host', 'port'))); + $database = array_intersect_key($form_state['values']['_database'], array_flip(array('driver', 'database', 'username', 'password', 'host', 'port', 'prefix'))); // Update global settings array and save $settings['databases'] = array( 'value' => array('default' => array('default' => $database)), 'required' => TRUE, ); - $settings['db_prefix'] = array( - 'value' => $form_state['values']['db_prefix'], - 'required' => TRUE, - ); drupal_rewrite_settings($settings); // Indicate that the settings file has been verified, and check the database // for the last completed task, now that we have a valid connection. This === modified file 'modules/simpletest/drupal_web_test_case.php' --- modules/simpletest/drupal_web_test_case.php 2009-10-11 03:07:16 +0000 +++ modules/simpletest/drupal_web_test_case.php 2009-10-12 22:17:35 +0000 @@ -15,11 +15,11 @@ abstract class DrupalTestCase { protected $testId; /** - * The original database prefix, before it was changed for testing purposes. + * The database prefix of this test run. * * @var string */ - protected $originalPrefix = NULL; + protected $databasePrefix = NULL; /** * The original file directory, before it was changed for testing purposes. @@ -90,8 +90,6 @@ abstract class DrupalTestCase { * is the caller function itself. */ protected function assert($status, $message = '', $group = 'Other', array $caller = NULL) { - global $db_prefix; - // Convert boolean status to string status. if (is_bool($status)) { $status = $status ? 'pass' : 'fail'; @@ -105,10 +103,6 @@ abstract class DrupalTestCase { $caller = $this->getAssertionCall(); } - // Switch to non-testing database to store results in. - $current_db_prefix = $db_prefix; - $db_prefix = $this->originalPrefix; - // Creation assertion array that can be displayed while tests are running. $this->assertions[] = $assertion = array( 'test_id' => $this->testId, @@ -122,12 +116,11 @@ abstract class DrupalTestCase { ); // Store assertion for display after the test has completed. - db_insert('simpletest') + Database::getConnection('default', 'simpletest_original_default') + ->insert('simpletest') ->fields($assertion) ->execute(); - // Return to testing prefix. - $db_prefix = $current_db_prefix; // We do not use a ternary operator here to allow a breakpoint on // test failure. if ($status == 'pass') { @@ -1025,27 +1018,39 @@ class DrupalWebTestCase extends DrupalTe * List of modules to enable for the duration of the test. */ protected function setUp() { - global $db_prefix, $user, $language; + global $user, $language; + + // Generate a temporary prefixed database to ensure that tests have a clean starting point. + $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000); + + // Clone the current connection and replace the current prefix. + $connection_info = Database::getConnectionInfo('default'); + Database::renameConnection('default', 'simpletest_original_default'); + foreach ($connection_info as $target => $value) { + $connection_info[$target]['prefix'] = array( + 'default' => $value['prefix']['default'] . $this->databasePrefix, + ); + } + Database::addConnectionInfo('default', 'default', $connection_info['default']); // Store necessary current values before switching to prefixed database. $this->originalLanguage = $language; $this->originalLanguageDefault = variable_get('language_default'); - $this->originalPrefix = $db_prefix; $this->originalFileDirectory = file_directory_path(); $this->originalProfile = drupal_get_profile(); $clean_url_original = variable_get('clean_url', 0); - // Generate temporary prefixed database to ensure that tests have a clean starting point. - $db_prefix_new = Database::getConnection()->prefixTables('{simpletest' . mt_rand(1000, 1000000) . '}'); + // Set the simpletest id for use in other parts of Drupal. + drupal_test_info(array('test_run_id' => $this->databasePrefix, 'in_child_site' => FALSE)); + db_update('simpletest_test_id') - ->fields(array('last_prefix' => $db_prefix_new)) + ->fields(array('last_prefix' => $this->databasePrefix)) ->condition('test_id', $this->testId) ->execute(); - $db_prefix = $db_prefix_new; // Create test directory ahead of installation so fatal errors and debug // information can be logged during installation process. - $directory = $this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10); + $directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10); file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS); // Log fatal errors. @@ -1109,7 +1114,7 @@ class DrupalWebTestCase extends DrupalTe variable_set('mail_sending_system', array('default-system' => 'TestingMailSystem')); // Use temporary files directory with the same prefix as the database. - $public_files_directory = $this->originalFileDirectory . '/' . $db_prefix; + $public_files_directory = $this->originalFileDirectory . '/' . $this->databasePrefix; $private_files_directory = $public_files_directory . '/private'; // Set path variables @@ -1130,8 +1135,10 @@ class DrupalWebTestCase extends DrupalTe * setup a clean environment for the current test run. */ protected function preloadRegistry() { - db_query('INSERT INTO {registry} SELECT * FROM ' . $this->originalPrefix . 'registry'); - db_query('INSERT INTO {registry_file} SELECT * FROM ' . $this->originalPrefix . 'registry_file'); + $original_connection = Database::getConnection('default', 'simpletest_original_default'); + $this->pass('INSERT INTO {registry} SELECT * FROM ' . $original_connection->prefixTables('{registry}')); + db_query('INSERT INTO {registry} SELECT * FROM ' . $original_connection->prefixTables('{registry}')); + db_query('INSERT INTO {registry_file} SELECT * FROM ' . $original_connection->prefixTables('{registry_file}')); } /** @@ -1157,7 +1164,7 @@ class DrupalWebTestCase extends DrupalTe * and reset the database prefix. */ protected function tearDown() { - global $db_prefix, $user, $language; + global $user, $language; // In case a fatal error occured that was not in the test process read the // log to pick up any fatal errors. @@ -1172,48 +1179,69 @@ class DrupalWebTestCase extends DrupalTe $this->pass($message, t('E-mail')); } - if (preg_match('/simpletest\d+/', $db_prefix)) { - // Delete temporary files directory. - file_unmanaged_delete_recursive(file_directory_path()); + // Delete temporary files directory. + file_unmanaged_delete_recursive(file_directory_path()); - // Remove all prefixed tables (all the tables in the schema). - $schema = drupal_get_schema(NULL, TRUE); - $ret = array(); - foreach ($schema as $name => $table) { - db_drop_table($name); - } - - // Return the database prefix to the original. - $db_prefix = $this->originalPrefix; - - // Return the user to the original one. - $user = $this->originalUser; - drupal_save_session(TRUE); + // Remove all prefixed tables (all the tables in the schema). + $schema = drupal_get_schema(NULL, TRUE); + $ret = array(); + foreach ($schema as $name => $table) { + db_drop_table($name); + } + + // Return the user to the original one. + $user = $this->originalUser; + drupal_save_session(TRUE); + + // Ensure that internal logged in variable and cURL options are reset. + $this->loggedInUser = FALSE; + $this->additionalCurlOptions = array(); + + // Reload module list and implementations to ensure that test module hooks + // aren't called after tests. + module_list(TRUE); + module_implements('', FALSE, TRUE); - // Ensure that internal logged in variable and cURL options are reset. - $this->loggedInUser = FALSE; - $this->additionalCurlOptions = array(); + // Reset the Field API. + field_cache_clear(); - // Reload module list and implementations to ensure that test module hooks - // aren't called after tests. - module_list(TRUE); - module_implements('', FALSE, TRUE); + // Rebuild caches. + $this->refreshVariables(); - // Reset the Field API. - field_cache_clear(); + // Reset language. + $language = $this->originalLanguage; + if ($this->originalLanguageDefault) { + $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; + } + + // Close the CURL handler. + $this->curlClose(); + + // Get back to the original connection. + Database::removeConnection('default'); + Database::renameConnection('simpletest_original_default', 'default'); + + // Return the user to the original one. + $user = $this->originalUser; + drupal_save_session(TRUE); + + // Ensure that internal logged in variable and cURL options are reset. + $this->isLoggedIn = FALSE; + $this->additionalCurlOptions = array(); + + // Reload module list and implementations to ensure that test module hooks + // aren't called after tests. + module_list(TRUE); + module_implements(MODULE_IMPLEMENTS_CLEAR_CACHE); - // Rebuild caches. - $this->refreshVariables(); + // Reset the Field API. + field_cache_clear(); - // Reset language. - $language = $this->originalLanguage; - if ($this->originalLanguageDefault) { - $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; - } + // Rebuild caches. + $this->refreshVariables(); - // Close the CURL handler. - $this->curlClose(); - } + // Close the CURL handler. + $this->curlClose(); } /** @@ -1225,7 +1253,7 @@ class DrupalWebTestCase extends DrupalTe * See the description of $curl_options for other options. */ protected function curlInitialize() { - global $base_url, $db_prefix; + global $base_url; if (!isset($this->curlHandle)) { $this->curlHandle = curl_init(); @@ -1238,6 +1266,7 @@ class DrupalWebTestCase extends DrupalTe CURLOPT_SSL_VERIFYPEER => FALSE, // Required to make the tests run on https. CURLOPT_SSL_VERIFYHOST => FALSE, // Required to make the tests run on https. CURLOPT_HEADERFUNCTION => array(&$this, 'curlHeaderCallback'), + CURLOPT_USERAGENT => $this->databasePrefix, ); if (isset($this->httpauth_credentials)) { $curl_options[CURLOPT_USERPWD] = $this->httpauth_credentials; === modified file 'sites/default/default.settings.php' --- sites/default/default.settings.php 2009-10-09 07:48:06 +0000 +++ sites/default/default.settings.php 2009-10-12 21:34:27 +0000 @@ -61,6 +61,7 @@ * 'password' => 'password', * 'host' => 'localhost', * 'port' => 3306, + * 'prefix' => 'myprefix_', * ); * * The "driver" property indicates what Drupal database driver the @@ -105,30 +106,31 @@ * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', + * 'prefix' => 'main_', * ); * * You can optionally set prefixes for some or all database table names - * by using the $db_prefix setting. If a prefix is specified, the table + * by using the 'prefix' setting. If a prefix is specified, the table * name will be prepended with its value. Be sure to use valid database * characters only, usually alphanumeric and underscore. If no prefixes * are desired, leave it as an empty string ''. * - * To have all database names prefixed, set $db_prefix as a string: + * To have all database names prefixed, set 'prefix' as a string: * - * $db_prefix = 'main_'; + * 'prefix' => 'main_', * - * To provide prefixes for specific tables, set $db_prefix as an array. + * To provide prefixes for specific tables, set 'prefix' as an array. * The array's keys are the table names and the values are the prefixes. - * The 'default' element holds the prefix for any tables not specified - * elsewhere in the array. Example: + * The 'default' element is mandatory and holds the prefix for any tables + * not specified elsewhere in the array. Example: * - * $db_prefix = array( + * 'prefix' = array( * 'default' => 'main_', * 'users' => 'shared_', * 'sessions' => 'shared_', * 'role' => 'shared_', * 'authmap' => 'shared_', - * ); + * ), * * Database configuration format: * $databases['default']['default'] = array( @@ -137,6 +139,7 @@ * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', + * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'pgsql', @@ -144,6 +147,7 @@ * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', + * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'sqlite', @@ -151,7 +155,6 @@ * ); */ $databases = array(); -$db_prefix = ''; /** * Access control for update.php script