annotate core/lib/Drupal/Core/Database/Connection.php @ 13:5fb285c0d0e3

Update Drupal core to 8.4.7 via Composer. Security update; I *think* we've been lucky to get away with this so far, as we don't support self-registration which seems to be used by the so-called "drupalgeddon 2" attack that 8.4.5 was vulnerable to.
author Chris Cannam
date Mon, 23 Apr 2018 09:33:26 +0100
parents 4c8ae668cc8c
children 129ea1e6d783
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Core\Database;
Chris@0 4
Chris@0 5 /**
Chris@0 6 * Base Database API class.
Chris@0 7 *
Chris@0 8 * This class provides a Drupal-specific extension of the PDO database
Chris@0 9 * abstraction class in PHP. Every database driver implementation must provide a
Chris@0 10 * concrete implementation of it to support special handling required by that
Chris@0 11 * database.
Chris@0 12 *
Chris@0 13 * @see http://php.net/manual/book.pdo.php
Chris@0 14 */
Chris@0 15 abstract class Connection {
Chris@0 16
Chris@0 17 /**
Chris@0 18 * The database target this connection is for.
Chris@0 19 *
Chris@0 20 * We need this information for later auditing and logging.
Chris@0 21 *
Chris@0 22 * @var string|null
Chris@0 23 */
Chris@0 24 protected $target = NULL;
Chris@0 25
Chris@0 26 /**
Chris@0 27 * The key representing this connection.
Chris@0 28 *
Chris@0 29 * The key is a unique string which identifies a database connection. A
Chris@0 30 * connection can be a single server or a cluster of primary and replicas
Chris@0 31 * (use target to pick between primary and replica).
Chris@0 32 *
Chris@0 33 * @var string|null
Chris@0 34 */
Chris@0 35 protected $key = NULL;
Chris@0 36
Chris@0 37 /**
Chris@0 38 * The current database logging object for this connection.
Chris@0 39 *
Chris@0 40 * @var \Drupal\Core\Database\Log|null
Chris@0 41 */
Chris@0 42 protected $logger = NULL;
Chris@0 43
Chris@0 44 /**
Chris@0 45 * Tracks the number of "layers" of transactions currently active.
Chris@0 46 *
Chris@0 47 * On many databases transactions cannot nest. Instead, we track
Chris@0 48 * nested calls to transactions and collapse them into a single
Chris@0 49 * transaction.
Chris@0 50 *
Chris@0 51 * @var array
Chris@0 52 */
Chris@0 53 protected $transactionLayers = [];
Chris@0 54
Chris@0 55 /**
Chris@0 56 * Index of what driver-specific class to use for various operations.
Chris@0 57 *
Chris@0 58 * @var array
Chris@0 59 */
Chris@0 60 protected $driverClasses = [];
Chris@0 61
Chris@0 62 /**
Chris@0 63 * The name of the Statement class for this connection.
Chris@0 64 *
Chris@0 65 * @var string
Chris@0 66 */
Chris@0 67 protected $statementClass = 'Drupal\Core\Database\Statement';
Chris@0 68
Chris@0 69 /**
Chris@0 70 * Whether this database connection supports transactions.
Chris@0 71 *
Chris@0 72 * @var bool
Chris@0 73 */
Chris@0 74 protected $transactionSupport = TRUE;
Chris@0 75
Chris@0 76 /**
Chris@0 77 * Whether this database connection supports transactional DDL.
Chris@0 78 *
Chris@0 79 * Set to FALSE by default because few databases support this feature.
Chris@0 80 *
Chris@0 81 * @var bool
Chris@0 82 */
Chris@0 83 protected $transactionalDDLSupport = FALSE;
Chris@0 84
Chris@0 85 /**
Chris@0 86 * An index used to generate unique temporary table names.
Chris@0 87 *
Chris@0 88 * @var int
Chris@0 89 */
Chris@0 90 protected $temporaryNameIndex = 0;
Chris@0 91
Chris@0 92 /**
Chris@0 93 * The actual PDO connection.
Chris@0 94 *
Chris@0 95 * @var \PDO
Chris@0 96 */
Chris@0 97 protected $connection;
Chris@0 98
Chris@0 99 /**
Chris@0 100 * The connection information for this connection object.
Chris@0 101 *
Chris@0 102 * @var array
Chris@0 103 */
Chris@0 104 protected $connectionOptions = [];
Chris@0 105
Chris@0 106 /**
Chris@0 107 * The schema object for this connection.
Chris@0 108 *
Chris@0 109 * Set to NULL when the schema is destroyed.
Chris@0 110 *
Chris@0 111 * @var \Drupal\Core\Database\Schema|null
Chris@0 112 */
Chris@0 113 protected $schema = NULL;
Chris@0 114
Chris@0 115 /**
Chris@0 116 * The prefixes used by this database connection.
Chris@0 117 *
Chris@0 118 * @var array
Chris@0 119 */
Chris@0 120 protected $prefixes = [];
Chris@0 121
Chris@0 122 /**
Chris@0 123 * List of search values for use in prefixTables().
Chris@0 124 *
Chris@0 125 * @var array
Chris@0 126 */
Chris@0 127 protected $prefixSearch = [];
Chris@0 128
Chris@0 129 /**
Chris@0 130 * List of replacement values for use in prefixTables().
Chris@0 131 *
Chris@0 132 * @var array
Chris@0 133 */
Chris@0 134 protected $prefixReplace = [];
Chris@0 135
Chris@0 136 /**
Chris@0 137 * List of un-prefixed table names, keyed by prefixed table names.
Chris@0 138 *
Chris@0 139 * @var array
Chris@0 140 */
Chris@0 141 protected $unprefixedTablesMap = [];
Chris@0 142
Chris@0 143 /**
Chris@0 144 * List of escaped database, table, and field names, keyed by unescaped names.
Chris@0 145 *
Chris@0 146 * @var array
Chris@0 147 */
Chris@0 148 protected $escapedNames = [];
Chris@0 149
Chris@0 150 /**
Chris@0 151 * List of escaped aliases names, keyed by unescaped aliases.
Chris@0 152 *
Chris@0 153 * @var array
Chris@0 154 */
Chris@0 155 protected $escapedAliases = [];
Chris@0 156
Chris@0 157 /**
Chris@0 158 * Constructs a Connection object.
Chris@0 159 *
Chris@0 160 * @param \PDO $connection
Chris@0 161 * An object of the PDO class representing a database connection.
Chris@0 162 * @param array $connection_options
Chris@0 163 * An array of options for the connection. May include the following:
Chris@0 164 * - prefix
Chris@0 165 * - namespace
Chris@0 166 * - Other driver-specific options.
Chris@0 167 */
Chris@0 168 public function __construct(\PDO $connection, array $connection_options) {
Chris@0 169 // Initialize and prepare the connection prefix.
Chris@0 170 $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : '');
Chris@0 171
Chris@0 172 // Set a Statement class, unless the driver opted out.
Chris@0 173 if (!empty($this->statementClass)) {
Chris@0 174 $connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]);
Chris@0 175 }
Chris@0 176
Chris@0 177 $this->connection = $connection;
Chris@0 178 $this->connectionOptions = $connection_options;
Chris@0 179 }
Chris@0 180
Chris@0 181 /**
Chris@0 182 * Opens a PDO connection.
Chris@0 183 *
Chris@0 184 * @param array $connection_options
Chris@0 185 * The database connection settings array.
Chris@0 186 *
Chris@0 187 * @return \PDO
Chris@0 188 * A \PDO object.
Chris@0 189 */
Chris@0 190 public static function open(array &$connection_options = []) {}
Chris@0 191
Chris@0 192 /**
Chris@0 193 * Destroys this Connection object.
Chris@0 194 *
Chris@0 195 * PHP does not destruct an object if it is still referenced in other
Chris@0 196 * variables. In case of PDO database connection objects, PHP only closes the
Chris@0 197 * connection when the PDO object is destructed, so any references to this
Chris@0 198 * object may cause the number of maximum allowed connections to be exceeded.
Chris@0 199 */
Chris@0 200 public function destroy() {
Chris@0 201 // Destroy all references to this connection by setting them to NULL.
Chris@0 202 // The Statement class attribute only accepts a new value that presents a
Chris@0 203 // proper callable, so we reset it to PDOStatement.
Chris@0 204 if (!empty($this->statementClass)) {
Chris@0 205 $this->connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['PDOStatement', []]);
Chris@0 206 }
Chris@0 207 $this->schema = NULL;
Chris@0 208 }
Chris@0 209
Chris@0 210 /**
Chris@0 211 * Returns the default query options for any given query.
Chris@0 212 *
Chris@0 213 * A given query can be customized with a number of option flags in an
Chris@0 214 * associative array:
Chris@0 215 * - target: The database "target" against which to execute a query. Valid
Chris@0 216 * values are "default" or "replica". The system will first try to open a
Chris@0 217 * connection to a database specified with the user-supplied key. If one
Chris@0 218 * is not available, it will silently fall back to the "default" target.
Chris@0 219 * If multiple databases connections are specified with the same target,
Chris@0 220 * one will be selected at random for the duration of the request.
Chris@0 221 * - fetch: This element controls how rows from a result set will be
Chris@0 222 * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
Chris@0 223 * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
Chris@0 224 * class. If a string is specified, each record will be fetched into a new
Chris@0 225 * object of that class. The behavior of all other values is defined by PDO.
Chris@0 226 * See http://php.net/manual/pdostatement.fetch.php
Chris@0 227 * - return: Depending on the type of query, different return values may be
Chris@0 228 * meaningful. This directive instructs the system which type of return
Chris@0 229 * value is desired. The system will generally set the correct value
Chris@0 230 * automatically, so it is extremely rare that a module developer will ever
Chris@0 231 * need to specify this value. Setting it incorrectly will likely lead to
Chris@0 232 * unpredictable results or fatal errors. Legal values include:
Chris@0 233 * - Database::RETURN_STATEMENT: Return the prepared statement object for
Chris@0 234 * the query. This is usually only meaningful for SELECT queries, where
Chris@0 235 * the statement object is how one accesses the result set returned by the
Chris@0 236 * query.
Chris@0 237 * - Database::RETURN_AFFECTED: Return the number of rows affected by an
Chris@0 238 * UPDATE or DELETE query. Be aware that means the number of rows actually
Chris@0 239 * changed, not the number of rows matched by the WHERE clause.
Chris@0 240 * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
Chris@0 241 * created by an INSERT statement on a table that contains a serial
Chris@0 242 * column.
Chris@0 243 * - Database::RETURN_NULL: Do not return anything, as there is no
Chris@0 244 * meaningful value to return. That is the case for INSERT queries on
Chris@0 245 * tables that do not contain a serial column.
Chris@0 246 * - throw_exception: By default, the database system will catch any errors
Chris@0 247 * on a query as an Exception, log it, and then rethrow it so that code
Chris@0 248 * further up the call chain can take an appropriate action. To suppress
Chris@0 249 * that behavior and simply return NULL on failure, set this option to
Chris@0 250 * FALSE.
Chris@0 251 * - allow_delimiter_in_query: By default, queries which have the ; delimiter
Chris@0 252 * any place in them will cause an exception. This reduces the chance of SQL
Chris@0 253 * injection attacks that terminate the original query and add one or more
Chris@0 254 * additional queries (such as inserting new user accounts). In rare cases,
Chris@0 255 * such as creating an SQL function, a ; is needed and can be allowed by
Chris@0 256 * changing this option to TRUE.
Chris@0 257 *
Chris@0 258 * @return array
Chris@0 259 * An array of default query options.
Chris@0 260 */
Chris@0 261 protected function defaultOptions() {
Chris@0 262 return [
Chris@0 263 'target' => 'default',
Chris@0 264 'fetch' => \PDO::FETCH_OBJ,
Chris@0 265 'return' => Database::RETURN_STATEMENT,
Chris@0 266 'throw_exception' => TRUE,
Chris@0 267 'allow_delimiter_in_query' => FALSE,
Chris@0 268 ];
Chris@0 269 }
Chris@0 270
Chris@0 271 /**
Chris@0 272 * Returns the connection information for this connection object.
Chris@0 273 *
Chris@0 274 * Note that Database::getConnectionInfo() is for requesting information
Chris@0 275 * about an arbitrary database connection that is defined. This method
Chris@0 276 * is for requesting the connection information of this specific
Chris@0 277 * open connection object.
Chris@0 278 *
Chris@0 279 * @return array
Chris@0 280 * An array of the connection information. The exact list of
Chris@0 281 * properties is driver-dependent.
Chris@0 282 */
Chris@0 283 public function getConnectionOptions() {
Chris@0 284 return $this->connectionOptions;
Chris@0 285 }
Chris@0 286
Chris@0 287 /**
Chris@0 288 * Set the list of prefixes used by this database connection.
Chris@0 289 *
Chris@0 290 * @param array|string $prefix
Chris@0 291 * Either a single prefix, or an array of prefixes, in any of the multiple
Chris@0 292 * forms documented in default.settings.php.
Chris@0 293 */
Chris@0 294 protected function setPrefix($prefix) {
Chris@0 295 if (is_array($prefix)) {
Chris@0 296 $this->prefixes = $prefix + ['default' => ''];
Chris@0 297 }
Chris@0 298 else {
Chris@0 299 $this->prefixes = ['default' => $prefix];
Chris@0 300 }
Chris@0 301
Chris@0 302 // Set up variables for use in prefixTables(). Replace table-specific
Chris@0 303 // prefixes first.
Chris@0 304 $this->prefixSearch = [];
Chris@0 305 $this->prefixReplace = [];
Chris@0 306 foreach ($this->prefixes as $key => $val) {
Chris@0 307 if ($key != 'default') {
Chris@0 308 $this->prefixSearch[] = '{' . $key . '}';
Chris@0 309 $this->prefixReplace[] = $val . $key;
Chris@0 310 }
Chris@0 311 }
Chris@0 312 // Then replace remaining tables with the default prefix.
Chris@0 313 $this->prefixSearch[] = '{';
Chris@0 314 $this->prefixReplace[] = $this->prefixes['default'];
Chris@0 315 $this->prefixSearch[] = '}';
Chris@0 316 $this->prefixReplace[] = '';
Chris@0 317
Chris@0 318 // Set up a map of prefixed => un-prefixed tables.
Chris@0 319 foreach ($this->prefixes as $table_name => $prefix) {
Chris@0 320 if ($table_name !== 'default') {
Chris@0 321 $this->unprefixedTablesMap[$prefix . $table_name] = $table_name;
Chris@0 322 }
Chris@0 323 }
Chris@0 324 }
Chris@0 325
Chris@0 326 /**
Chris@0 327 * Appends a database prefix to all tables in a query.
Chris@0 328 *
Chris@0 329 * Queries sent to Drupal should wrap all table names in curly brackets. This
Chris@0 330 * function searches for this syntax and adds Drupal's table prefix to all
Chris@0 331 * tables, allowing Drupal to coexist with other systems in the same database
Chris@0 332 * and/or schema if necessary.
Chris@0 333 *
Chris@0 334 * @param string $sql
Chris@0 335 * A string containing a partial or entire SQL query.
Chris@0 336 *
Chris@0 337 * @return string
Chris@0 338 * The properly-prefixed string.
Chris@0 339 */
Chris@0 340 public function prefixTables($sql) {
Chris@0 341 return str_replace($this->prefixSearch, $this->prefixReplace, $sql);
Chris@0 342 }
Chris@0 343
Chris@0 344 /**
Chris@0 345 * Find the prefix for a table.
Chris@0 346 *
Chris@0 347 * This function is for when you want to know the prefix of a table. This
Chris@0 348 * is not used in prefixTables due to performance reasons.
Chris@0 349 *
Chris@0 350 * @param string $table
Chris@0 351 * (optional) The table to find the prefix for.
Chris@0 352 */
Chris@0 353 public function tablePrefix($table = 'default') {
Chris@0 354 if (isset($this->prefixes[$table])) {
Chris@0 355 return $this->prefixes[$table];
Chris@0 356 }
Chris@0 357 else {
Chris@0 358 return $this->prefixes['default'];
Chris@0 359 }
Chris@0 360 }
Chris@0 361
Chris@0 362 /**
Chris@0 363 * Gets a list of individually prefixed table names.
Chris@0 364 *
Chris@0 365 * @return array
Chris@0 366 * An array of un-prefixed table names, keyed by their fully qualified table
Chris@0 367 * names (i.e. prefix + table_name).
Chris@0 368 */
Chris@0 369 public function getUnprefixedTablesMap() {
Chris@0 370 return $this->unprefixedTablesMap;
Chris@0 371 }
Chris@0 372
Chris@0 373 /**
Chris@0 374 * Get a fully qualified table name.
Chris@0 375 *
Chris@0 376 * @param string $table
Chris@0 377 * The name of the table in question.
Chris@0 378 *
Chris@0 379 * @return string
Chris@0 380 */
Chris@0 381 public function getFullQualifiedTableName($table) {
Chris@0 382 $options = $this->getConnectionOptions();
Chris@0 383 $prefix = $this->tablePrefix($table);
Chris@0 384 return $options['database'] . '.' . $prefix . $table;
Chris@0 385 }
Chris@0 386
Chris@0 387 /**
Chris@0 388 * Prepares a query string and returns the prepared statement.
Chris@0 389 *
Chris@0 390 * This method caches prepared statements, reusing them when
Chris@0 391 * possible. It also prefixes tables names enclosed in curly-braces.
Chris@0 392 *
Chris@0 393 * @param $query
Chris@0 394 * The query string as SQL, with curly-braces surrounding the
Chris@0 395 * table names.
Chris@0 396 *
Chris@0 397 * @return \Drupal\Core\Database\StatementInterface
Chris@0 398 * A PDO prepared statement ready for its execute() method.
Chris@0 399 */
Chris@0 400 public function prepareQuery($query) {
Chris@0 401 $query = $this->prefixTables($query);
Chris@0 402
Chris@0 403 return $this->connection->prepare($query);
Chris@0 404 }
Chris@0 405
Chris@0 406 /**
Chris@0 407 * Tells this connection object what its target value is.
Chris@0 408 *
Chris@0 409 * This is needed for logging and auditing. It's sloppy to do in the
Chris@0 410 * constructor because the constructor for child classes has a different
Chris@0 411 * signature. We therefore also ensure that this function is only ever
Chris@0 412 * called once.
Chris@0 413 *
Chris@0 414 * @param string $target
Chris@0 415 * (optional) The target this connection is for.
Chris@0 416 */
Chris@0 417 public function setTarget($target = NULL) {
Chris@0 418 if (!isset($this->target)) {
Chris@0 419 $this->target = $target;
Chris@0 420 }
Chris@0 421 }
Chris@0 422
Chris@0 423 /**
Chris@0 424 * Returns the target this connection is associated with.
Chris@0 425 *
Chris@0 426 * @return string|null
Chris@0 427 * The target string of this connection, or NULL if no target is set.
Chris@0 428 */
Chris@0 429 public function getTarget() {
Chris@0 430 return $this->target;
Chris@0 431 }
Chris@0 432
Chris@0 433 /**
Chris@0 434 * Tells this connection object what its key is.
Chris@0 435 *
Chris@0 436 * @param string $key
Chris@0 437 * The key this connection is for.
Chris@0 438 */
Chris@0 439 public function setKey($key) {
Chris@0 440 if (!isset($this->key)) {
Chris@0 441 $this->key = $key;
Chris@0 442 }
Chris@0 443 }
Chris@0 444
Chris@0 445 /**
Chris@0 446 * Returns the key this connection is associated with.
Chris@0 447 *
Chris@0 448 * @return string|null
Chris@0 449 * The key of this connection, or NULL if no key is set.
Chris@0 450 */
Chris@0 451 public function getKey() {
Chris@0 452 return $this->key;
Chris@0 453 }
Chris@0 454
Chris@0 455 /**
Chris@0 456 * Associates a logging object with this connection.
Chris@0 457 *
Chris@0 458 * @param \Drupal\Core\Database\Log $logger
Chris@0 459 * The logging object we want to use.
Chris@0 460 */
Chris@0 461 public function setLogger(Log $logger) {
Chris@0 462 $this->logger = $logger;
Chris@0 463 }
Chris@0 464
Chris@0 465 /**
Chris@0 466 * Gets the current logging object for this connection.
Chris@0 467 *
Chris@0 468 * @return \Drupal\Core\Database\Log|null
Chris@0 469 * The current logging object for this connection. If there isn't one,
Chris@0 470 * NULL is returned.
Chris@0 471 */
Chris@0 472 public function getLogger() {
Chris@0 473 return $this->logger;
Chris@0 474 }
Chris@0 475
Chris@0 476 /**
Chris@0 477 * Creates the appropriate sequence name for a given table and serial field.
Chris@0 478 *
Chris@0 479 * This information is exposed to all database drivers, although it is only
Chris@0 480 * useful on some of them. This method is table prefix-aware.
Chris@0 481 *
Chris@0 482 * @param string $table
Chris@0 483 * The table name to use for the sequence.
Chris@0 484 * @param string $field
Chris@0 485 * The field name to use for the sequence.
Chris@0 486 *
Chris@0 487 * @return string
Chris@0 488 * A table prefix-parsed string for the sequence name.
Chris@0 489 */
Chris@0 490 public function makeSequenceName($table, $field) {
Chris@0 491 return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
Chris@0 492 }
Chris@0 493
Chris@0 494 /**
Chris@0 495 * Flatten an array of query comments into a single comment string.
Chris@0 496 *
Chris@0 497 * The comment string will be sanitized to avoid SQL injection attacks.
Chris@0 498 *
Chris@0 499 * @param string[] $comments
Chris@0 500 * An array of query comment strings.
Chris@0 501 *
Chris@0 502 * @return string
Chris@0 503 * A sanitized comment string.
Chris@0 504 */
Chris@0 505 public function makeComment($comments) {
Chris@0 506 if (empty($comments)) {
Chris@0 507 return '';
Chris@0 508 }
Chris@0 509
Chris@0 510 // Flatten the array of comments.
Chris@0 511 $comment = implode('. ', $comments);
Chris@0 512
Chris@0 513 // Sanitize the comment string so as to avoid SQL injection attacks.
Chris@0 514 return '/* ' . $this->filterComment($comment) . ' */ ';
Chris@0 515 }
Chris@0 516
Chris@0 517 /**
Chris@0 518 * Sanitize a query comment string.
Chris@0 519 *
Chris@0 520 * Ensure a query comment does not include strings such as "* /" that might
Chris@0 521 * terminate the comment early. This avoids SQL injection attacks via the
Chris@0 522 * query comment. The comment strings in this example are separated by a
Chris@0 523 * space to avoid PHP parse errors.
Chris@0 524 *
Chris@0 525 * For example, the comment:
Chris@0 526 * @code
Chris@0 527 * db_update('example')
Chris@0 528 * ->condition('id', $id)
Chris@0 529 * ->fields(array('field2' => 10))
Chris@0 530 * ->comment('Exploit * / DROP TABLE node; --')
Chris@0 531 * ->execute()
Chris@0 532 * @endcode
Chris@0 533 *
Chris@0 534 * Would result in the following SQL statement being generated:
Chris@0 535 * @code
Chris@0 536 * "/ * Exploit * / DROP TABLE node. -- * / UPDATE example SET field2=..."
Chris@0 537 * @endcode
Chris@0 538 *
Chris@0 539 * Unless the comment is sanitised first, the SQL server would drop the
Chris@0 540 * node table and ignore the rest of the SQL statement.
Chris@0 541 *
Chris@0 542 * @param string $comment
Chris@0 543 * A query comment string.
Chris@0 544 *
Chris@0 545 * @return string
Chris@0 546 * A sanitized version of the query comment string.
Chris@0 547 */
Chris@0 548 protected function filterComment($comment = '') {
Chris@0 549 // Change semicolons to period to avoid triggering multi-statement check.
Chris@0 550 return strtr($comment, ['*' => ' * ', ';' => '.']);
Chris@0 551 }
Chris@0 552
Chris@0 553 /**
Chris@0 554 * Executes a query string against the database.
Chris@0 555 *
Chris@0 556 * This method provides a central handler for the actual execution of every
Chris@0 557 * query. All queries executed by Drupal are executed as PDO prepared
Chris@0 558 * statements.
Chris@0 559 *
Chris@0 560 * @param string|\Drupal\Core\Database\StatementInterface $query
Chris@0 561 * The query to execute. In most cases this will be a string containing
Chris@0 562 * an SQL query with placeholders. An already-prepared instance of
Chris@0 563 * StatementInterface may also be passed in order to allow calling
Chris@0 564 * code to manually bind variables to a query. If a
Chris@0 565 * StatementInterface is passed, the $args array will be ignored.
Chris@0 566 * It is extremely rare that module code will need to pass a statement
Chris@0 567 * object to this method. It is used primarily for database drivers for
Chris@0 568 * databases that require special LOB field handling.
Chris@0 569 * @param array $args
Chris@0 570 * An array of arguments for the prepared statement. If the prepared
Chris@0 571 * statement uses ? placeholders, this array must be an indexed array.
Chris@0 572 * If it contains named placeholders, it must be an associative array.
Chris@0 573 * @param array $options
Chris@0 574 * An associative array of options to control how the query is run. The
Chris@0 575 * given options will be merged with self::defaultOptions(). See the
Chris@0 576 * documentation for self::defaultOptions() for details.
Chris@0 577 * Typically, $options['return'] will be set by a default or by a query
Chris@0 578 * builder, and should not be set by a user.
Chris@0 579 *
Chris@0 580 * @return \Drupal\Core\Database\StatementInterface|int|null
Chris@0 581 * This method will return one of the following:
Chris@0 582 * - If either $options['return'] === self::RETURN_STATEMENT, or
Chris@0 583 * $options['return'] is not set (due to self::defaultOptions()),
Chris@0 584 * returns the executed statement.
Chris@0 585 * - If $options['return'] === self::RETURN_AFFECTED,
Chris@0 586 * returns the number of rows affected by the query
Chris@0 587 * (not the number matched).
Chris@0 588 * - If $options['return'] === self::RETURN_INSERT_ID,
Chris@0 589 * returns the generated insert ID of the last query.
Chris@0 590 * - If either $options['return'] === self::RETURN_NULL, or
Chris@0 591 * an exception occurs and $options['throw_exception'] evaluates to FALSE,
Chris@0 592 * returns NULL.
Chris@0 593 *
Chris@0 594 * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
Chris@0 595 * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
Chris@0 596 * @throws \InvalidArgumentException
Chris@0 597 *
Chris@0 598 * @see \Drupal\Core\Database\Connection::defaultOptions()
Chris@0 599 */
Chris@0 600 public function query($query, array $args = [], $options = []) {
Chris@0 601 // Use default values if not already set.
Chris@0 602 $options += $this->defaultOptions();
Chris@0 603
Chris@0 604 try {
Chris@0 605 // We allow either a pre-bound statement object or a literal string.
Chris@0 606 // In either case, we want to end up with an executed statement object,
Chris@0 607 // which we pass to PDOStatement::execute.
Chris@0 608 if ($query instanceof StatementInterface) {
Chris@0 609 $stmt = $query;
Chris@0 610 $stmt->execute(NULL, $options);
Chris@0 611 }
Chris@0 612 else {
Chris@0 613 $this->expandArguments($query, $args);
Chris@0 614 // To protect against SQL injection, Drupal only supports executing one
Chris@0 615 // statement at a time. Thus, the presence of a SQL delimiter (the
Chris@0 616 // semicolon) is not allowed unless the option is set. Allowing
Chris@0 617 // semicolons should only be needed for special cases like defining a
Chris@0 618 // function or stored procedure in SQL. Trim any trailing delimiter to
Chris@0 619 // minimize false positives.
Chris@0 620 $query = rtrim($query, "; \t\n\r\0\x0B");
Chris@0 621 if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
Chris@0 622 throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
Chris@0 623 }
Chris@0 624 $stmt = $this->prepareQuery($query);
Chris@0 625 $stmt->execute($args, $options);
Chris@0 626 }
Chris@0 627
Chris@0 628 // Depending on the type of query we may need to return a different value.
Chris@0 629 // See DatabaseConnection::defaultOptions() for a description of each
Chris@0 630 // value.
Chris@0 631 switch ($options['return']) {
Chris@0 632 case Database::RETURN_STATEMENT:
Chris@0 633 return $stmt;
Chris@0 634 case Database::RETURN_AFFECTED:
Chris@0 635 $stmt->allowRowCount = TRUE;
Chris@0 636 return $stmt->rowCount();
Chris@0 637 case Database::RETURN_INSERT_ID:
Chris@0 638 $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
Chris@0 639 return $this->connection->lastInsertId($sequence_name);
Chris@0 640 case Database::RETURN_NULL:
Chris@0 641 return NULL;
Chris@0 642 default:
Chris@0 643 throw new \PDOException('Invalid return directive: ' . $options['return']);
Chris@0 644 }
Chris@0 645 }
Chris@0 646 catch (\PDOException $e) {
Chris@0 647 // Most database drivers will return NULL here, but some of them
Chris@0 648 // (e.g. the SQLite driver) may need to re-run the query, so the return
Chris@0 649 // value will be the same as for static::query().
Chris@0 650 return $this->handleQueryException($e, $query, $args, $options);
Chris@0 651 }
Chris@0 652 }
Chris@0 653
Chris@0 654 /**
Chris@0 655 * Wraps and re-throws any PDO exception thrown by static::query().
Chris@0 656 *
Chris@0 657 * @param \PDOException $e
Chris@0 658 * The exception thrown by static::query().
Chris@0 659 * @param $query
Chris@0 660 * The query executed by static::query().
Chris@0 661 * @param array $args
Chris@0 662 * An array of arguments for the prepared statement.
Chris@0 663 * @param array $options
Chris@0 664 * An associative array of options to control how the query is run.
Chris@0 665 *
Chris@0 666 * @return \Drupal\Core\Database\StatementInterface|int|null
Chris@0 667 * Most database drivers will return NULL when a PDO exception is thrown for
Chris@0 668 * a query, but some of them may need to re-run the query, so they can also
Chris@0 669 * return a \Drupal\Core\Database\StatementInterface object or an integer.
Chris@0 670 *
Chris@0 671 * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
Chris@0 672 * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
Chris@0 673 */
Chris@0 674 protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
Chris@0 675 if ($options['throw_exception']) {
Chris@0 676 // Wrap the exception in another exception, because PHP does not allow
Chris@0 677 // overriding Exception::getMessage(). Its message is the extra database
Chris@0 678 // debug information.
Chris@0 679 $query_string = ($query instanceof StatementInterface) ? $query->getQueryString() : $query;
Chris@0 680 $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE);
Chris@0 681 // Match all SQLSTATE 23xxx errors.
Chris@0 682 if (substr($e->getCode(), -6, -3) == '23') {
Chris@0 683 $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e);
Chris@0 684 }
Chris@0 685 else {
Chris@0 686 $exception = new DatabaseExceptionWrapper($message, 0, $e);
Chris@0 687 }
Chris@0 688
Chris@0 689 throw $exception;
Chris@0 690 }
Chris@0 691
Chris@0 692 return NULL;
Chris@0 693 }
Chris@0 694
Chris@0 695 /**
Chris@0 696 * Expands out shorthand placeholders.
Chris@0 697 *
Chris@0 698 * Drupal supports an alternate syntax for doing arrays of values. We
Chris@0 699 * therefore need to expand them out into a full, executable query string.
Chris@0 700 *
Chris@0 701 * @param string $query
Chris@0 702 * The query string to modify.
Chris@0 703 * @param array $args
Chris@0 704 * The arguments for the query.
Chris@0 705 *
Chris@0 706 * @return bool
Chris@0 707 * TRUE if the query was modified, FALSE otherwise.
Chris@0 708 *
Chris@0 709 * @throws \InvalidArgumentException
Chris@0 710 * This exception is thrown when:
Chris@0 711 * - A placeholder that ends in [] is supplied, and the supplied value is
Chris@0 712 * not an array.
Chris@0 713 * - A placeholder that does not end in [] is supplied, and the supplied
Chris@0 714 * value is an array.
Chris@0 715 */
Chris@0 716 protected function expandArguments(&$query, &$args) {
Chris@0 717 $modified = FALSE;
Chris@0 718
Chris@0 719 // If the placeholder indicated the value to use is an array, we need to
Chris@0 720 // expand it out into a comma-delimited set of placeholders.
Chris@0 721 foreach ($args as $key => $data) {
Chris@0 722 $is_bracket_placeholder = substr($key, -2) === '[]';
Chris@0 723 $is_array_data = is_array($data);
Chris@0 724 if ($is_bracket_placeholder && !$is_array_data) {
Chris@0 725 throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.');
Chris@0 726 }
Chris@0 727 elseif (!$is_bracket_placeholder) {
Chris@0 728 if ($is_array_data) {
Chris@0 729 throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.');
Chris@0 730 }
Chris@0 731 // Scalar placeholder - does not need to be expanded.
Chris@0 732 continue;
Chris@0 733 }
Chris@0 734 // Handle expansion of arrays.
Chris@0 735 $key_name = str_replace('[]', '__', $key);
Chris@0 736 $new_keys = [];
Chris@0 737 // We require placeholders to have trailing brackets if the developer
Chris@0 738 // intends them to be expanded to an array to make the intent explicit.
Chris@0 739 foreach (array_values($data) as $i => $value) {
Chris@0 740 // This assumes that there are no other placeholders that use the same
Chris@0 741 // name. For example, if the array placeholder is defined as :example[]
Chris@0 742 // and there is already an :example_2 placeholder, this will generate
Chris@0 743 // a duplicate key. We do not account for that as the calling code
Chris@0 744 // is already broken if that happens.
Chris@0 745 $new_keys[$key_name . $i] = $value;
Chris@0 746 }
Chris@0 747
Chris@0 748 // Update the query with the new placeholders.
Chris@0 749 $query = str_replace($key, implode(', ', array_keys($new_keys)), $query);
Chris@0 750
Chris@0 751 // Update the args array with the new placeholders.
Chris@0 752 unset($args[$key]);
Chris@0 753 $args += $new_keys;
Chris@0 754
Chris@0 755 $modified = TRUE;
Chris@0 756 }
Chris@0 757
Chris@0 758 return $modified;
Chris@0 759 }
Chris@0 760
Chris@0 761 /**
Chris@0 762 * Gets the driver-specific override class if any for the specified class.
Chris@0 763 *
Chris@0 764 * @param string $class
Chris@0 765 * The class for which we want the potentially driver-specific class.
Chris@0 766 * @return string
Chris@0 767 * The name of the class that should be used for this driver.
Chris@0 768 */
Chris@0 769 public function getDriverClass($class) {
Chris@0 770 if (empty($this->driverClasses[$class])) {
Chris@0 771 if (empty($this->connectionOptions['namespace'])) {
Chris@0 772 // Fallback for Drupal 7 settings.php and the test runner script.
Chris@0 773 $this->connectionOptions['namespace'] = (new \ReflectionObject($this))->getNamespaceName();
Chris@0 774 }
Chris@0 775 $driver_class = $this->connectionOptions['namespace'] . '\\' . $class;
Chris@0 776 $this->driverClasses[$class] = class_exists($driver_class) ? $driver_class : $class;
Chris@0 777 }
Chris@0 778 return $this->driverClasses[$class];
Chris@0 779 }
Chris@0 780
Chris@0 781 /**
Chris@0 782 * Prepares and returns a SELECT query object.
Chris@0 783 *
Chris@0 784 * @param string $table
Chris@0 785 * The base table for this query, that is, the first table in the FROM
Chris@0 786 * clause. This table will also be used as the "base" table for query_alter
Chris@0 787 * hook implementations.
Chris@0 788 * @param string $alias
Chris@0 789 * (optional) The alias of the base table of this query.
Chris@0 790 * @param $options
Chris@0 791 * An array of options on the query.
Chris@0 792 *
Chris@0 793 * @return \Drupal\Core\Database\Query\SelectInterface
Chris@0 794 * An appropriate SelectQuery object for this database connection. Note that
Chris@0 795 * it may be a driver-specific subclass of SelectQuery, depending on the
Chris@0 796 * driver.
Chris@0 797 *
Chris@0 798 * @see \Drupal\Core\Database\Query\Select
Chris@0 799 */
Chris@0 800 public function select($table, $alias = NULL, array $options = []) {
Chris@0 801 $class = $this->getDriverClass('Select');
Chris@0 802 return new $class($table, $alias, $this, $options);
Chris@0 803 }
Chris@0 804
Chris@0 805 /**
Chris@0 806 * Prepares and returns an INSERT query object.
Chris@0 807 *
Chris@0 808 * @param string $table
Chris@0 809 * The table to use for the insert statement.
Chris@0 810 * @param array $options
Chris@0 811 * (optional) An array of options on the query.
Chris@0 812 *
Chris@0 813 * @return \Drupal\Core\Database\Query\Insert
Chris@0 814 * A new Insert query object.
Chris@0 815 *
Chris@0 816 * @see \Drupal\Core\Database\Query\Insert
Chris@0 817 */
Chris@0 818 public function insert($table, array $options = []) {
Chris@0 819 $class = $this->getDriverClass('Insert');
Chris@0 820 return new $class($this, $table, $options);
Chris@0 821 }
Chris@0 822
Chris@0 823 /**
Chris@0 824 * Prepares and returns a MERGE query object.
Chris@0 825 *
Chris@0 826 * @param string $table
Chris@0 827 * The table to use for the merge statement.
Chris@0 828 * @param array $options
Chris@0 829 * (optional) An array of options on the query.
Chris@0 830 *
Chris@0 831 * @return \Drupal\Core\Database\Query\Merge
Chris@0 832 * A new Merge query object.
Chris@0 833 *
Chris@0 834 * @see \Drupal\Core\Database\Query\Merge
Chris@0 835 */
Chris@0 836 public function merge($table, array $options = []) {
Chris@0 837 $class = $this->getDriverClass('Merge');
Chris@0 838 return new $class($this, $table, $options);
Chris@0 839 }
Chris@0 840
Chris@0 841 /**
Chris@0 842 * Prepares and returns an UPSERT query object.
Chris@0 843 *
Chris@0 844 * @param string $table
Chris@0 845 * The table to use for the upsert query.
Chris@0 846 * @param array $options
Chris@0 847 * (optional) An array of options on the query.
Chris@0 848 *
Chris@0 849 * @return \Drupal\Core\Database\Query\Upsert
Chris@0 850 * A new Upsert query object.
Chris@0 851 *
Chris@0 852 * @see \Drupal\Core\Database\Query\Upsert
Chris@0 853 */
Chris@0 854 public function upsert($table, array $options = []) {
Chris@0 855 $class = $this->getDriverClass('Upsert');
Chris@0 856 return new $class($this, $table, $options);
Chris@0 857 }
Chris@0 858
Chris@0 859 /**
Chris@0 860 * Prepares and returns an UPDATE query object.
Chris@0 861 *
Chris@0 862 * @param string $table
Chris@0 863 * The table to use for the update statement.
Chris@0 864 * @param array $options
Chris@0 865 * (optional) An array of options on the query.
Chris@0 866 *
Chris@0 867 * @return \Drupal\Core\Database\Query\Update
Chris@0 868 * A new Update query object.
Chris@0 869 *
Chris@0 870 * @see \Drupal\Core\Database\Query\Update
Chris@0 871 */
Chris@0 872 public function update($table, array $options = []) {
Chris@0 873 $class = $this->getDriverClass('Update');
Chris@0 874 return new $class($this, $table, $options);
Chris@0 875 }
Chris@0 876
Chris@0 877 /**
Chris@0 878 * Prepares and returns a DELETE query object.
Chris@0 879 *
Chris@0 880 * @param string $table
Chris@0 881 * The table to use for the delete statement.
Chris@0 882 * @param array $options
Chris@0 883 * (optional) An array of options on the query.
Chris@0 884 *
Chris@0 885 * @return \Drupal\Core\Database\Query\Delete
Chris@0 886 * A new Delete query object.
Chris@0 887 *
Chris@0 888 * @see \Drupal\Core\Database\Query\Delete
Chris@0 889 */
Chris@0 890 public function delete($table, array $options = []) {
Chris@0 891 $class = $this->getDriverClass('Delete');
Chris@0 892 return new $class($this, $table, $options);
Chris@0 893 }
Chris@0 894
Chris@0 895 /**
Chris@0 896 * Prepares and returns a TRUNCATE query object.
Chris@0 897 *
Chris@0 898 * @param string $table
Chris@0 899 * The table to use for the truncate statement.
Chris@0 900 * @param array $options
Chris@0 901 * (optional) An array of options on the query.
Chris@0 902 *
Chris@0 903 * @return \Drupal\Core\Database\Query\Truncate
Chris@0 904 * A new Truncate query object.
Chris@0 905 *
Chris@0 906 * @see \Drupal\Core\Database\Query\Truncate
Chris@0 907 */
Chris@0 908 public function truncate($table, array $options = []) {
Chris@0 909 $class = $this->getDriverClass('Truncate');
Chris@0 910 return new $class($this, $table, $options);
Chris@0 911 }
Chris@0 912
Chris@0 913 /**
Chris@0 914 * Returns a DatabaseSchema object for manipulating the schema.
Chris@0 915 *
Chris@0 916 * This method will lazy-load the appropriate schema library file.
Chris@0 917 *
Chris@0 918 * @return \Drupal\Core\Database\Schema
Chris@0 919 * The database Schema object for this connection.
Chris@0 920 */
Chris@0 921 public function schema() {
Chris@0 922 if (empty($this->schema)) {
Chris@0 923 $class = $this->getDriverClass('Schema');
Chris@0 924 $this->schema = new $class($this);
Chris@0 925 }
Chris@0 926 return $this->schema;
Chris@0 927 }
Chris@0 928
Chris@0 929 /**
Chris@0 930 * Escapes a database name string.
Chris@0 931 *
Chris@0 932 * Force all database names to be strictly alphanumeric-plus-underscore.
Chris@0 933 * For some database drivers, it may also wrap the database name in
Chris@0 934 * database-specific escape characters.
Chris@0 935 *
Chris@0 936 * @param string $database
Chris@0 937 * An unsanitized database name.
Chris@0 938 *
Chris@0 939 * @return string
Chris@0 940 * The sanitized database name.
Chris@0 941 */
Chris@0 942 public function escapeDatabase($database) {
Chris@0 943 if (!isset($this->escapedNames[$database])) {
Chris@0 944 $this->escapedNames[$database] = preg_replace('/[^A-Za-z0-9_.]+/', '', $database);
Chris@0 945 }
Chris@0 946 return $this->escapedNames[$database];
Chris@0 947 }
Chris@0 948
Chris@0 949 /**
Chris@0 950 * Escapes a table name string.
Chris@0 951 *
Chris@0 952 * Force all table names to be strictly alphanumeric-plus-underscore.
Chris@0 953 * For some database drivers, it may also wrap the table name in
Chris@0 954 * database-specific escape characters.
Chris@0 955 *
Chris@0 956 * @param string $table
Chris@0 957 * An unsanitized table name.
Chris@0 958 *
Chris@0 959 * @return string
Chris@0 960 * The sanitized table name.
Chris@0 961 */
Chris@0 962 public function escapeTable($table) {
Chris@0 963 if (!isset($this->escapedNames[$table])) {
Chris@0 964 $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
Chris@0 965 }
Chris@0 966 return $this->escapedNames[$table];
Chris@0 967 }
Chris@0 968
Chris@0 969 /**
Chris@0 970 * Escapes a field name string.
Chris@0 971 *
Chris@0 972 * Force all field names to be strictly alphanumeric-plus-underscore.
Chris@0 973 * For some database drivers, it may also wrap the field name in
Chris@0 974 * database-specific escape characters.
Chris@0 975 *
Chris@0 976 * @param string $field
Chris@0 977 * An unsanitized field name.
Chris@0 978 *
Chris@0 979 * @return string
Chris@0 980 * The sanitized field name.
Chris@0 981 */
Chris@0 982 public function escapeField($field) {
Chris@0 983 if (!isset($this->escapedNames[$field])) {
Chris@0 984 $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
Chris@0 985 }
Chris@0 986 return $this->escapedNames[$field];
Chris@0 987 }
Chris@0 988
Chris@0 989 /**
Chris@0 990 * Escapes an alias name string.
Chris@0 991 *
Chris@0 992 * Force all alias names to be strictly alphanumeric-plus-underscore. In
Chris@0 993 * contrast to DatabaseConnection::escapeField() /
Chris@0 994 * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
Chris@0 995 * because that is not allowed in aliases.
Chris@0 996 *
Chris@0 997 * @param string $field
Chris@0 998 * An unsanitized alias name.
Chris@0 999 *
Chris@0 1000 * @return string
Chris@0 1001 * The sanitized alias name.
Chris@0 1002 */
Chris@0 1003 public function escapeAlias($field) {
Chris@0 1004 if (!isset($this->escapedAliases[$field])) {
Chris@0 1005 $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
Chris@0 1006 }
Chris@0 1007 return $this->escapedAliases[$field];
Chris@0 1008 }
Chris@0 1009
Chris@0 1010 /**
Chris@0 1011 * Escapes characters that work as wildcard characters in a LIKE pattern.
Chris@0 1012 *
Chris@0 1013 * The wildcard characters "%" and "_" as well as backslash are prefixed with
Chris@0 1014 * a backslash. Use this to do a search for a verbatim string without any
Chris@0 1015 * wildcard behavior.
Chris@0 1016 *
Chris@0 1017 * For example, the following does a case-insensitive query for all rows whose
Chris@0 1018 * name starts with $prefix:
Chris@0 1019 * @code
Chris@0 1020 * $result = db_query(
Chris@0 1021 * 'SELECT * FROM person WHERE name LIKE :pattern',
Chris@0 1022 * array(':pattern' => db_like($prefix) . '%')
Chris@0 1023 * );
Chris@0 1024 * @endcode
Chris@0 1025 *
Chris@0 1026 * Backslash is defined as escape character for LIKE patterns in
Chris@0 1027 * Drupal\Core\Database\Query\Condition::mapConditionOperator().
Chris@0 1028 *
Chris@0 1029 * @param string $string
Chris@0 1030 * The string to escape.
Chris@0 1031 *
Chris@0 1032 * @return string
Chris@0 1033 * The escaped string.
Chris@0 1034 */
Chris@0 1035 public function escapeLike($string) {
Chris@0 1036 return addcslashes($string, '\%_');
Chris@0 1037 }
Chris@0 1038
Chris@0 1039 /**
Chris@0 1040 * Determines if there is an active transaction open.
Chris@0 1041 *
Chris@0 1042 * @return bool
Chris@0 1043 * TRUE if we're currently in a transaction, FALSE otherwise.
Chris@0 1044 */
Chris@0 1045 public function inTransaction() {
Chris@0 1046 return ($this->transactionDepth() > 0);
Chris@0 1047 }
Chris@0 1048
Chris@0 1049 /**
Chris@0 1050 * Determines the current transaction depth.
Chris@0 1051 *
Chris@0 1052 * @return int
Chris@0 1053 * The current transaction depth.
Chris@0 1054 */
Chris@0 1055 public function transactionDepth() {
Chris@0 1056 return count($this->transactionLayers);
Chris@0 1057 }
Chris@0 1058
Chris@0 1059 /**
Chris@0 1060 * Returns a new DatabaseTransaction object on this connection.
Chris@0 1061 *
Chris@0 1062 * @param string $name
Chris@0 1063 * (optional) The name of the savepoint.
Chris@0 1064 *
Chris@0 1065 * @return \Drupal\Core\Database\Transaction
Chris@0 1066 * A Transaction object.
Chris@0 1067 *
Chris@0 1068 * @see \Drupal\Core\Database\Transaction
Chris@0 1069 */
Chris@0 1070 public function startTransaction($name = '') {
Chris@0 1071 $class = $this->getDriverClass('Transaction');
Chris@0 1072 return new $class($this, $name);
Chris@0 1073 }
Chris@0 1074
Chris@0 1075 /**
Chris@0 1076 * Rolls back the transaction entirely or to a named savepoint.
Chris@0 1077 *
Chris@0 1078 * This method throws an exception if no transaction is active.
Chris@0 1079 *
Chris@0 1080 * @param string $savepoint_name
Chris@0 1081 * (optional) The name of the savepoint. The default, 'drupal_transaction',
Chris@0 1082 * will roll the entire transaction back.
Chris@0 1083 *
Chris@0 1084 * @throws \Drupal\Core\Database\TransactionOutOfOrderException
Chris@0 1085 * @throws \Drupal\Core\Database\TransactionNoActiveException
Chris@0 1086 *
Chris@0 1087 * @see \Drupal\Core\Database\Transaction::rollBack()
Chris@0 1088 */
Chris@0 1089 public function rollBack($savepoint_name = 'drupal_transaction') {
Chris@0 1090 if (!$this->supportsTransactions()) {
Chris@0 1091 return;
Chris@0 1092 }
Chris@0 1093 if (!$this->inTransaction()) {
Chris@0 1094 throw new TransactionNoActiveException();
Chris@0 1095 }
Chris@0 1096 // A previous rollback to an earlier savepoint may mean that the savepoint
Chris@0 1097 // in question has already been accidentally committed.
Chris@0 1098 if (!isset($this->transactionLayers[$savepoint_name])) {
Chris@0 1099 throw new TransactionNoActiveException();
Chris@0 1100 }
Chris@0 1101
Chris@0 1102 // We need to find the point we're rolling back to, all other savepoints
Chris@0 1103 // before are no longer needed. If we rolled back other active savepoints,
Chris@0 1104 // we need to throw an exception.
Chris@0 1105 $rolled_back_other_active_savepoints = FALSE;
Chris@0 1106 while ($savepoint = array_pop($this->transactionLayers)) {
Chris@0 1107 if ($savepoint == $savepoint_name) {
Chris@0 1108 // If it is the last the transaction in the stack, then it is not a
Chris@0 1109 // savepoint, it is the transaction itself so we will need to roll back
Chris@0 1110 // the transaction rather than a savepoint.
Chris@0 1111 if (empty($this->transactionLayers)) {
Chris@0 1112 break;
Chris@0 1113 }
Chris@0 1114 $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
Chris@0 1115 $this->popCommittableTransactions();
Chris@0 1116 if ($rolled_back_other_active_savepoints) {
Chris@0 1117 throw new TransactionOutOfOrderException();
Chris@0 1118 }
Chris@0 1119 return;
Chris@0 1120 }
Chris@0 1121 else {
Chris@0 1122 $rolled_back_other_active_savepoints = TRUE;
Chris@0 1123 }
Chris@0 1124 }
Chris@0 1125 $this->connection->rollBack();
Chris@0 1126 if ($rolled_back_other_active_savepoints) {
Chris@0 1127 throw new TransactionOutOfOrderException();
Chris@0 1128 }
Chris@0 1129 }
Chris@0 1130
Chris@0 1131 /**
Chris@0 1132 * Increases the depth of transaction nesting.
Chris@0 1133 *
Chris@0 1134 * If no transaction is already active, we begin a new transaction.
Chris@0 1135 *
Chris@0 1136 * @param string $name
Chris@0 1137 * The name of the transaction.
Chris@0 1138 *
Chris@0 1139 * @throws \Drupal\Core\Database\TransactionNameNonUniqueException
Chris@0 1140 *
Chris@0 1141 * @see \Drupal\Core\Database\Transaction
Chris@0 1142 */
Chris@0 1143 public function pushTransaction($name) {
Chris@0 1144 if (!$this->supportsTransactions()) {
Chris@0 1145 return;
Chris@0 1146 }
Chris@0 1147 if (isset($this->transactionLayers[$name])) {
Chris@0 1148 throw new TransactionNameNonUniqueException($name . " is already in use.");
Chris@0 1149 }
Chris@0 1150 // If we're already in a transaction then we want to create a savepoint
Chris@0 1151 // rather than try to create another transaction.
Chris@0 1152 if ($this->inTransaction()) {
Chris@0 1153 $this->query('SAVEPOINT ' . $name);
Chris@0 1154 }
Chris@0 1155 else {
Chris@0 1156 $this->connection->beginTransaction();
Chris@0 1157 }
Chris@0 1158 $this->transactionLayers[$name] = $name;
Chris@0 1159 }
Chris@0 1160
Chris@0 1161 /**
Chris@0 1162 * Decreases the depth of transaction nesting.
Chris@0 1163 *
Chris@0 1164 * If we pop off the last transaction layer, then we either commit or roll
Chris@0 1165 * back the transaction as necessary. If no transaction is active, we return
Chris@0 1166 * because the transaction may have manually been rolled back.
Chris@0 1167 *
Chris@0 1168 * @param string $name
Chris@0 1169 * The name of the savepoint.
Chris@0 1170 *
Chris@0 1171 * @throws \Drupal\Core\Database\TransactionNoActiveException
Chris@0 1172 * @throws \Drupal\Core\Database\TransactionCommitFailedException
Chris@0 1173 *
Chris@0 1174 * @see \Drupal\Core\Database\Transaction
Chris@0 1175 */
Chris@0 1176 public function popTransaction($name) {
Chris@0 1177 if (!$this->supportsTransactions()) {
Chris@0 1178 return;
Chris@0 1179 }
Chris@0 1180 // The transaction has already been committed earlier. There is nothing we
Chris@0 1181 // need to do. If this transaction was part of an earlier out-of-order
Chris@0 1182 // rollback, an exception would already have been thrown by
Chris@0 1183 // Database::rollBack().
Chris@0 1184 if (!isset($this->transactionLayers[$name])) {
Chris@0 1185 return;
Chris@0 1186 }
Chris@0 1187
Chris@0 1188 // Mark this layer as committable.
Chris@0 1189 $this->transactionLayers[$name] = FALSE;
Chris@0 1190 $this->popCommittableTransactions();
Chris@0 1191 }
Chris@0 1192
Chris@0 1193 /**
Chris@0 1194 * Internal function: commit all the transaction layers that can commit.
Chris@0 1195 */
Chris@0 1196 protected function popCommittableTransactions() {
Chris@0 1197 // Commit all the committable layers.
Chris@0 1198 foreach (array_reverse($this->transactionLayers) as $name => $active) {
Chris@0 1199 // Stop once we found an active transaction.
Chris@0 1200 if ($active) {
Chris@0 1201 break;
Chris@0 1202 }
Chris@0 1203
Chris@0 1204 // If there are no more layers left then we should commit.
Chris@0 1205 unset($this->transactionLayers[$name]);
Chris@0 1206 if (empty($this->transactionLayers)) {
Chris@0 1207 if (!$this->connection->commit()) {
Chris@0 1208 throw new TransactionCommitFailedException();
Chris@0 1209 }
Chris@0 1210 }
Chris@0 1211 else {
Chris@0 1212 $this->query('RELEASE SAVEPOINT ' . $name);
Chris@0 1213 }
Chris@0 1214 }
Chris@0 1215 }
Chris@0 1216
Chris@0 1217 /**
Chris@0 1218 * Runs a limited-range query on this database object.
Chris@0 1219 *
Chris@0 1220 * Use this as a substitute for ->query() when a subset of the query is to be
Chris@0 1221 * returned. User-supplied arguments to the query should be passed in as
Chris@0 1222 * separate parameters so that they can be properly escaped to avoid SQL
Chris@0 1223 * injection attacks.
Chris@0 1224 *
Chris@0 1225 * @param string $query
Chris@0 1226 * A string containing an SQL query.
Chris@0 1227 * @param int $from
Chris@0 1228 * The first result row to return.
Chris@0 1229 * @param int $count
Chris@0 1230 * The maximum number of result rows to return.
Chris@0 1231 * @param array $args
Chris@0 1232 * (optional) An array of values to substitute into the query at placeholder
Chris@0 1233 * markers.
Chris@0 1234 * @param array $options
Chris@0 1235 * (optional) An array of options on the query.
Chris@0 1236 *
Chris@0 1237 * @return \Drupal\Core\Database\StatementInterface
Chris@0 1238 * A database query result resource, or NULL if the query was not executed
Chris@0 1239 * correctly.
Chris@0 1240 */
Chris@0 1241 abstract public function queryRange($query, $from, $count, array $args = [], array $options = []);
Chris@0 1242
Chris@0 1243 /**
Chris@0 1244 * Generates a temporary table name.
Chris@0 1245 *
Chris@0 1246 * @return string
Chris@0 1247 * A table name.
Chris@0 1248 */
Chris@0 1249 protected function generateTemporaryTableName() {
Chris@0 1250 return "db_temporary_" . $this->temporaryNameIndex++;
Chris@0 1251 }
Chris@0 1252
Chris@0 1253 /**
Chris@0 1254 * Runs a SELECT query and stores its results in a temporary table.
Chris@0 1255 *
Chris@0 1256 * Use this as a substitute for ->query() when the results need to stored
Chris@0 1257 * in a temporary table. Temporary tables exist for the duration of the page
Chris@0 1258 * request. User-supplied arguments to the query should be passed in as
Chris@0 1259 * separate parameters so that they can be properly escaped to avoid SQL
Chris@0 1260 * injection attacks.
Chris@0 1261 *
Chris@0 1262 * Note that if you need to know how many results were returned, you should do
Chris@0 1263 * a SELECT COUNT(*) on the temporary table afterwards.
Chris@0 1264 *
Chris@0 1265 * @param string $query
Chris@0 1266 * A string containing a normal SELECT SQL query.
Chris@0 1267 * @param array $args
Chris@0 1268 * (optional) An array of values to substitute into the query at placeholder
Chris@0 1269 * markers.
Chris@0 1270 * @param array $options
Chris@0 1271 * (optional) An associative array of options to control how the query is
Chris@0 1272 * run. See the documentation for DatabaseConnection::defaultOptions() for
Chris@0 1273 * details.
Chris@0 1274 *
Chris@0 1275 * @return string
Chris@0 1276 * The name of the temporary table.
Chris@0 1277 */
Chris@0 1278 abstract public function queryTemporary($query, array $args = [], array $options = []);
Chris@0 1279
Chris@0 1280 /**
Chris@0 1281 * Returns the type of database driver.
Chris@0 1282 *
Chris@0 1283 * This is not necessarily the same as the type of the database itself. For
Chris@0 1284 * instance, there could be two MySQL drivers, mysql and mysql_mock. This
Chris@0 1285 * function would return different values for each, but both would return
Chris@0 1286 * "mysql" for databaseType().
Chris@0 1287 *
Chris@0 1288 * @return string
Chris@0 1289 * The type of database driver.
Chris@0 1290 */
Chris@0 1291 abstract public function driver();
Chris@0 1292
Chris@0 1293 /**
Chris@0 1294 * Returns the version of the database server.
Chris@0 1295 */
Chris@0 1296 public function version() {
Chris@0 1297 return $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION);
Chris@0 1298 }
Chris@0 1299
Chris@0 1300 /**
Chris@0 1301 * Returns the version of the database client.
Chris@0 1302 */
Chris@0 1303 public function clientVersion() {
Chris@0 1304 return $this->connection->getAttribute(\PDO::ATTR_CLIENT_VERSION);
Chris@0 1305 }
Chris@0 1306
Chris@0 1307 /**
Chris@0 1308 * Determines if this driver supports transactions.
Chris@0 1309 *
Chris@0 1310 * @return bool
Chris@0 1311 * TRUE if this connection supports transactions, FALSE otherwise.
Chris@0 1312 */
Chris@0 1313 public function supportsTransactions() {
Chris@0 1314 return $this->transactionSupport;
Chris@0 1315 }
Chris@0 1316
Chris@0 1317 /**
Chris@0 1318 * Determines if this driver supports transactional DDL.
Chris@0 1319 *
Chris@0 1320 * DDL queries are those that change the schema, such as ALTER queries.
Chris@0 1321 *
Chris@0 1322 * @return bool
Chris@0 1323 * TRUE if this connection supports transactions for DDL queries, FALSE
Chris@0 1324 * otherwise.
Chris@0 1325 */
Chris@0 1326 public function supportsTransactionalDDL() {
Chris@0 1327 return $this->transactionalDDLSupport;
Chris@0 1328 }
Chris@0 1329
Chris@0 1330 /**
Chris@0 1331 * Returns the name of the PDO driver for this connection.
Chris@0 1332 */
Chris@0 1333 abstract public function databaseType();
Chris@0 1334
Chris@0 1335 /**
Chris@0 1336 * Creates a database.
Chris@0 1337 *
Chris@0 1338 * In order to use this method, you must be connected without a database
Chris@0 1339 * specified.
Chris@0 1340 *
Chris@0 1341 * @param string $database
Chris@0 1342 * The name of the database to create.
Chris@0 1343 */
Chris@0 1344 abstract public function createDatabase($database);
Chris@0 1345
Chris@0 1346 /**
Chris@0 1347 * Gets any special processing requirements for the condition operator.
Chris@0 1348 *
Chris@0 1349 * Some condition types require special processing, such as IN, because
Chris@0 1350 * the value data they pass in is not a simple value. This is a simple
Chris@0 1351 * overridable lookup function. Database connections should define only
Chris@0 1352 * those operators they wish to be handled differently than the default.
Chris@0 1353 *
Chris@0 1354 * @param string $operator
Chris@0 1355 * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
Chris@0 1356 *
Chris@0 1357 * @return
Chris@0 1358 * The extra handling directives for the specified operator, or NULL.
Chris@0 1359 *
Chris@0 1360 * @see \Drupal\Core\Database\Query\Condition::compile()
Chris@0 1361 */
Chris@0 1362 abstract public function mapConditionOperator($operator);
Chris@0 1363
Chris@0 1364 /**
Chris@0 1365 * Throws an exception to deny direct access to transaction commits.
Chris@0 1366 *
Chris@0 1367 * We do not want to allow users to commit transactions at any time, only
Chris@0 1368 * by destroying the transaction object or allowing it to go out of scope.
Chris@0 1369 * A direct commit bypasses all of the safety checks we've built on top of
Chris@0 1370 * PDO's transaction routines.
Chris@0 1371 *
Chris@0 1372 * @throws \Drupal\Core\Database\TransactionExplicitCommitNotAllowedException
Chris@0 1373 *
Chris@0 1374 * @see \Drupal\Core\Database\Transaction
Chris@0 1375 */
Chris@0 1376 public function commit() {
Chris@0 1377 throw new TransactionExplicitCommitNotAllowedException();
Chris@0 1378 }
Chris@0 1379
Chris@0 1380 /**
Chris@0 1381 * Retrieves an unique ID from a given sequence.
Chris@0 1382 *
Chris@0 1383 * Use this function if for some reason you can't use a serial field. For
Chris@0 1384 * example, MySQL has no ways of reading of the current value of a sequence
Chris@0 1385 * and PostgreSQL can not advance the sequence to be larger than a given
Chris@0 1386 * value. Or sometimes you just need a unique integer.
Chris@0 1387 *
Chris@0 1388 * @param $existing_id
Chris@0 1389 * (optional) After a database import, it might be that the sequences table
Chris@0 1390 * is behind, so by passing in the maximum existing ID, it can be assured
Chris@0 1391 * that we never issue the same ID.
Chris@0 1392 *
Chris@0 1393 * @return
Chris@0 1394 * An integer number larger than any number returned by earlier calls and
Chris@0 1395 * also larger than the $existing_id if one was passed in.
Chris@0 1396 */
Chris@0 1397 abstract public function nextId($existing_id = 0);
Chris@0 1398
Chris@0 1399 /**
Chris@0 1400 * Prepares a statement for execution and returns a statement object
Chris@0 1401 *
Chris@0 1402 * Emulated prepared statements does not communicate with the database server
Chris@0 1403 * so this method does not check the statement.
Chris@0 1404 *
Chris@0 1405 * @param string $statement
Chris@0 1406 * This must be a valid SQL statement for the target database server.
Chris@0 1407 * @param array $driver_options
Chris@0 1408 * (optional) This array holds one or more key=>value pairs to set
Chris@0 1409 * attribute values for the PDOStatement object that this method returns.
Chris@0 1410 * You would most commonly use this to set the \PDO::ATTR_CURSOR value to
Chris@0 1411 * \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have
Chris@0 1412 * driver specific options that may be set at prepare-time. Defaults to an
Chris@0 1413 * empty array.
Chris@0 1414 *
Chris@0 1415 * @return \PDOStatement|false
Chris@0 1416 * If the database server successfully prepares the statement, returns a
Chris@0 1417 * \PDOStatement object.
Chris@0 1418 * If the database server cannot successfully prepare the statement returns
Chris@0 1419 * FALSE or emits \PDOException (depending on error handling).
Chris@0 1420 *
Chris@0 1421 * @throws \PDOException
Chris@0 1422 *
Chris@0 1423 * @see \PDO::prepare()
Chris@0 1424 */
Chris@0 1425 public function prepare($statement, array $driver_options = []) {
Chris@0 1426 return $this->connection->prepare($statement, $driver_options);
Chris@0 1427 }
Chris@0 1428
Chris@0 1429 /**
Chris@0 1430 * Quotes a string for use in a query.
Chris@0 1431 *
Chris@0 1432 * @param string $string
Chris@0 1433 * The string to be quoted.
Chris@0 1434 * @param int $parameter_type
Chris@0 1435 * (optional) Provides a data type hint for drivers that have alternate
Chris@0 1436 * quoting styles. Defaults to \PDO::PARAM_STR.
Chris@0 1437 *
Chris@0 1438 * @return string|bool
Chris@0 1439 * A quoted string that is theoretically safe to pass into an SQL statement.
Chris@0 1440 * Returns FALSE if the driver does not support quoting in this way.
Chris@0 1441 *
Chris@0 1442 * @see \PDO::quote()
Chris@0 1443 */
Chris@0 1444 public function quote($string, $parameter_type = \PDO::PARAM_STR) {
Chris@0 1445 return $this->connection->quote($string, $parameter_type);
Chris@0 1446 }
Chris@0 1447
Chris@0 1448 /**
Chris@0 1449 * Extracts the SQLSTATE error from the PDOException.
Chris@0 1450 *
Chris@0 1451 * @param \Exception $e
Chris@0 1452 * The exception
Chris@0 1453 *
Chris@0 1454 * @return string
Chris@0 1455 * The five character error code.
Chris@0 1456 */
Chris@0 1457 protected static function getSQLState(\Exception $e) {
Chris@0 1458 // The PDOException code is not always reliable, try to see whether the
Chris@0 1459 // message has something usable.
Chris@0 1460 if (preg_match('/^SQLSTATE\[(\w{5})\]/', $e->getMessage(), $matches)) {
Chris@0 1461 return $matches[1];
Chris@0 1462 }
Chris@0 1463 else {
Chris@0 1464 return $e->getCode();
Chris@0 1465 }
Chris@0 1466 }
Chris@0 1467
Chris@0 1468 /**
Chris@0 1469 * Prevents the database connection from being serialized.
Chris@0 1470 */
Chris@0 1471 public function __sleep() {
Chris@0 1472 throw new \LogicException('The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution.');
Chris@0 1473 }
Chris@0 1474
Chris@0 1475 }