Database.php 13.4 KB
Newer Older
1 2
<?php

Crell's avatar
Crell committed
3 4 5 6 7
/**
 * @file
 * Definition of Drupal\Core\Database\Database
 */

8
namespace Drupal\Core\Database;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

/**
 * Primary front-controller for the database system.
 *
 * This class is uninstantiatable and un-extendable. It acts to encapsulate
 * all control and shepherding of database connections into a single location
 * without the use of globals.
 */
abstract class Database {

  /**
   * Flag to indicate a query call should simply return NULL.
   *
   * This is used for queries that have no reasonable return value anyway, such
   * as INSERT statements to a table without a serial primary key.
   */
  const RETURN_NULL = 0;

  /**
   * Flag to indicate a query call should return the prepared statement.
   */
  const RETURN_STATEMENT = 1;

  /**
   * Flag to indicate a query call should return the number of affected rows.
   */
  const RETURN_AFFECTED = 2;

  /**
   * Flag to indicate a query call should return the "last insert id".
   */
  const RETURN_INSERT_ID = 3;

  /**
   * An nested array of all active connections. It is keyed by database name
   * and target.
   *
   * @var array
   */
  static protected $connections = array();

  /**
   * A processed copy of the database connection information from settings.php.
   *
   * @var array
   */
55
  static protected $databaseInfo = array();
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

  /**
   * A list of key/target credentials to simply ignore.
   *
   * @var array
   */
  static protected $ignoreTargets = array();

  /**
   * The key of the currently active database connection.
   *
   * @var string
   */
  static protected $activeKey = 'default';

  /**
   * An array of active query log objects.
   *
   * Every connection has one and only one logger object for all targets and
   * logging keys.
   *
   * array(
   *   '$db_key' => DatabaseLog object.
   * );
   *
   * @var array
   */
  static protected $logs = array();

  /**
   * Starts logging a given logging key on the specified connection.
   *
88
   * @param string $logging_key
89
   *   The logging key to log.
90
   * @param string $key
91 92
   *   The database connection key for which we want to log.
   *
93
   * @return \Drupal\Core\Database\Log
94 95 96 97
   *   The query log object. Note that the log object does support richer
   *   methods than the few exposed through the Database class, so in some
   *   cases it may be desirable to access it directly.
   *
98
   * @see \Drupal\Core\Database\Log
99 100 101
   */
  final public static function startLog($logging_key, $key = 'default') {
    if (empty(self::$logs[$key])) {
102
      self::$logs[$key] = new Log($key);
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

      // Every target already active for this connection key needs to have the
      // logging object associated with it.
      if (!empty(self::$connections[$key])) {
        foreach (self::$connections[$key] as $connection) {
          $connection->setLogger(self::$logs[$key]);
        }
      }
    }

    self::$logs[$key]->start($logging_key);
    return self::$logs[$key];
  }

  /**
   * Retrieves the queries logged on for given logging key.
   *
   * This method also ends logging for the specified key. To get the query log
   * to date without ending the logger request the logging object by starting
   * it again (which does nothing to an open log key) and call methods on it as
   * desired.
   *
125
   * @param string $logging_key
126
   *   The logging key to log.
127
   * @param string $key
128 129 130 131 132
   *   The database connection key for which we want to log.
   *
   * @return array
   *   The query log for the specified logging key and connection.
   *
133
   * @see \Drupal\Core\Database\Log
134 135 136 137 138 139 140 141 142 143 144 145 146
   */
  final public static function getLog($logging_key, $key = 'default') {
    if (empty(self::$logs[$key])) {
      return NULL;
    }
    $queries = self::$logs[$key]->get($logging_key);
    self::$logs[$key]->end($logging_key);
    return $queries;
  }

  /**
   * Gets the connection object for the specified database key and target.
   *
147
   * @param string $target
148
   *   The database target name.
149
   * @param string $key
150 151
   *   The database connection key. Defaults to NULL which means the active key.
   *
152
   * @return \Drupal\Core\Database\Connection
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
   *   The corresponding connection object.
   */
  final public static function getConnection($target = 'default', $key = NULL) {
    if (!isset($key)) {
      // By default, we want the active connection, set in setActiveConnection.
      $key = self::$activeKey;
    }
    // If the requested target does not exist, or if it is ignored, we fall back
    // to the default target. The target is typically either "default" or
    // "slave", indicating to use a slave SQL server if one is available. If
    // it's not available, then the default/master server is the correct server
    // to use.
    if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
      $target = 'default';
    }

    if (!isset(self::$connections[$key][$target])) {
      // If necessary, a new connection is opened.
      self::$connections[$key][$target] = self::openConnection($key, $target);
    }
    return self::$connections[$key][$target];
  }

  /**
   * Determines if there is an active connection.
   *
   * Note that this method will return FALSE if no connection has been
   * established yet, even if one could be.
   *
182
   * @return bool
183 184 185 186 187 188 189 190 191 192
   *   TRUE if there is at least one database connection established, FALSE
   *   otherwise.
   */
  final public static function isActiveConnection() {
    return !empty(self::$activeKey) && !empty(self::$connections) && !empty(self::$connections[self::$activeKey]);
  }

  /**
   * Sets the active connection to the specified key.
   *
193
   * @return string|null
194 195 196 197 198 199 200 201 202 203 204 205
   *   The previous database connection key.
   */
  final public static function setActiveConnection($key = 'default') {
    if (!empty(self::$databaseInfo[$key])) {
      $old_key = self::$activeKey;
      self::$activeKey = $key;
      return $old_key;
    }
  }

  /**
   * Process the configuration file for database information.
206 207 208 209 210
   *
   * @param array $info
   *   The database connection information, as defined in settings.php. The
   *   structure of this array depends on the database driver it is connecting
   *   to.
211
   */
212 213 214 215 216 217
  final public static function parseConnectionInfo(array $info) {
    // If there is no "driver" property, then we assume it's an array of
    // possible connections for this target. Pick one at random. That allows
    // us to have, for example, multiple slave servers.
    if (empty($info['driver'])) {
      $info = $info[mt_rand(0, count($info) - 1)];
218
    }
219 220 221 222 223 224
    // Parse the prefix information.
    if (!isset($info['prefix'])) {
      // Default to an empty prefix.
      $info['prefix'] = array(
        'default' => '',
      );
225
    }
226 227 228 229 230
    elseif (!is_array($info['prefix'])) {
      // Transform the flat form into an array form.
      $info['prefix'] = array(
        'default' => $info['prefix'],
      );
231
    }
232
    return $info;
233 234 235 236 237
  }

  /**
   * Adds database connection information for a given key/target.
   *
238 239
   * This method allows to add new connections at runtime.
   *
240 241 242 243 244 245 246
   * Under normal circumstances the preferred way to specify database
   * credentials is via settings.php. However, this method allows them to be
   * added at arbitrary times, such as during unit tests, when connecting to
   * admin-defined third party databases, etc.
   *
   * If the given key/target pair already exists, this method will be ignored.
   *
247
   * @param string $key
248
   *   The database key.
249
   * @param string $target
250
   *   The database target name.
251 252 253 254
   * @param array $info
   *   The database connection information, as defined in settings.php. The
   *   structure of this array depends on the database driver it is connecting
   *   to.
255
   */
256
  final public static function addConnectionInfo($key, $target, array $info) {
257
    if (empty(self::$databaseInfo[$key][$target])) {
258
      self::$databaseInfo[$key][$target] = self::parseConnectionInfo($info);
259 260 261 262 263 264
    }
  }

  /**
   * Gets information on the specified database connection.
   *
265 266 267 268
   * @param string $key
   *   (optional) The connection key for which to return information.
   *
   * @return array|null
269 270 271 272 273 274 275
   */
  final public static function getConnectionInfo($key = 'default') {
    if (!empty(self::$databaseInfo[$key])) {
      return self::$databaseInfo[$key];
    }
  }

276 277 278 279 280 281 282 283 284 285 286 287 288 289
  /**
   * Sets database connection information.
   *
   * @param array $databases
   *   A multi-dimensional array specifying database connection parameters.
   */
  final public static function setConnectionInfo(array $databases) {
    foreach ($databases as $key => $targets) {
      foreach ($targets as $target => $info) {
        self::addConnectionInfo($key, $target, $info);
      }
    }
  }

290 291 292
  /**
   * Rename a connection and its corresponding connection information.
   *
293
   * @param string $old_key
294
   *   The old connection key.
295
   * @param string $new_key
296
   *   The new connection key.
297 298
   *
   * @return bool
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
   *   TRUE in case of success, FALSE otherwise.
   */
  final public static function renameConnection($old_key, $new_key) {
    if (!empty(self::$databaseInfo[$old_key]) && empty(self::$databaseInfo[$new_key])) {
      // Migrate the database connection information.
      self::$databaseInfo[$new_key] = self::$databaseInfo[$old_key];
      unset(self::$databaseInfo[$old_key]);

      // Migrate over the DatabaseConnection object if it exists.
      if (isset(self::$connections[$old_key])) {
        self::$connections[$new_key] = self::$connections[$old_key];
        unset(self::$connections[$old_key]);
      }

      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Remove a connection and its corresponding connection information.
   *
323
   * @param string $key
324
   *   The connection key.
325 326
   *
   * @return bool
327 328 329 330
   *   TRUE in case of success, FALSE otherwise.
   */
  final public static function removeConnection($key) {
    if (isset(self::$databaseInfo[$key])) {
331
      self::closeConnection(NULL, $key);
332 333 334 335 336 337 338 339 340 341 342
      unset(self::$databaseInfo[$key]);
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Opens a connection to the server specified by the given key and target.
   *
343
   * @param string $key
344 345
   *   The database connection key, as specified in settings.php. The default is
   *   "default".
346
   * @param string $target
347 348
   *   The database target to open.
   *
349 350
   * @throws \Drupal\Core\Database\ConnectionNotDefinedException
   * @throws \Drupal\Core\Database\DriverNotSpecifiedException
351 352 353 354 355
   */
  final protected static function openConnection($key, $target) {
    // If the requested database does not exist then it is an unrecoverable
    // error.
    if (!isset(self::$databaseInfo[$key])) {
356
      throw new ConnectionNotDefinedException('The specified database connection is not defined: ' . $key);
357 358 359
    }

    if (!$driver = self::$databaseInfo[$key][$target]['driver']) {
360
      throw new DriverNotSpecifiedException('Driver not specified for this database connection: ' . $key);
361 362
    }

363 364 365 366 367 368 369
    if (!empty(self::$databaseInfo[$key][$target]['namespace'])) {
      $driver_class = self::$databaseInfo[$key][$target]['namespace'] . '\\Connection';
    }
    else {
      // Fallback for Drupal 7 settings.php.
      $driver_class = "Drupal\\Core\\Database\\Driver\\{$driver}\\Connection";
    }
370 371 372

    $pdo_connection = $driver_class::open(self::$databaseInfo[$key][$target]);
    $new_connection = new $driver_class($pdo_connection, self::$databaseInfo[$key][$target]);
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    $new_connection->setTarget($target);
    $new_connection->setKey($key);

    // If we have any active logging objects for this connection key, we need
    // to associate them with the connection we just opened.
    if (!empty(self::$logs[$key])) {
      $new_connection->setLogger(self::$logs[$key]);
    }

    return $new_connection;
  }

  /**
   * Closes a connection to the server specified by the given key and target.
   *
388
   * @param string $target
389 390
   *   The database target name.  Defaults to NULL meaning that all target
   *   connections will be closed.
391
   * @param string $key
392 393 394 395 396 397 398
   *   The database connection key. Defaults to NULL which means the active key.
   */
  public static function closeConnection($target = NULL, $key = NULL) {
    // Gets the active connection by default.
    if (!isset($key)) {
      $key = self::$activeKey;
    }
399 400 401 402
    // To close a connection, it needs to be set to NULL and removed from the
    // static variable. In all cases, closeConnection() might be called for a
    // connection that was not opened yet, in which case the key is not defined
    // yet and we just ensure that the connection key is undefined.
403
    if (isset($target)) {
404 405 406 407
      if (isset(self::$connections[$key][$target])) {
        self::$connections[$key][$target]->destroy();
        self::$connections[$key][$target] = NULL;
      }
408 409 410
      unset(self::$connections[$key][$target]);
    }
    else {
411 412 413 414 415 416
      if (isset(self::$connections[$key])) {
        foreach (self::$connections[$key] as $target => $connection) {
          self::$connections[$key][$target]->destroy();
          self::$connections[$key][$target] = NULL;
        }
      }
417 418 419 420 421 422 423 424 425 426 427
      unset(self::$connections[$key]);
    }
  }

  /**
   * Instructs the system to temporarily ignore a given key/target.
   *
   * At times we need to temporarily disable slave queries. To do so, call this
   * method with the database key and the target to disable. That database key
   * will then always fall back to 'default' for that key, even if it's defined.
   *
428
   * @param string $key
429
   *   The database connection key.
430
   * @param string $target
431 432 433 434 435 436
   *   The target of the specified key to ignore.
   */
  public static function ignoreTarget($key, $target) {
    self::$ignoreTargets[$key][$target] = TRUE;
  }
}