3 namespace Drupal\Core\Database;
6 * Base Database API class.
8 * This class provides a Drupal-specific extension of the PDO database
9 * abstraction class in PHP. Every database driver implementation must provide a
10 * concrete implementation of it to support special handling required by that
13 * @see http://php.net/manual/book.pdo.php
15 abstract class Connection {
18 * The database target this connection is for.
20 * We need this information for later auditing and logging.
24 protected $target = NULL;
27 * The key representing this connection.
29 * The key is a unique string which identifies a database connection. A
30 * connection can be a single server or a cluster of primary and replicas
31 * (use target to pick between primary and replica).
35 protected $key = NULL;
38 * The current database logging object for this connection.
40 * @var \Drupal\Core\Database\Log|null
42 protected $logger = NULL;
45 * Tracks the number of "layers" of transactions currently active.
47 * On many databases transactions cannot nest. Instead, we track
48 * nested calls to transactions and collapse them into a single
53 protected $transactionLayers = [];
56 * Index of what driver-specific class to use for various operations.
60 protected $driverClasses = [];
63 * The name of the Statement class for this connection.
67 protected $statementClass = 'Drupal\Core\Database\Statement';
70 * Whether this database connection supports transactions.
74 protected $transactionSupport = TRUE;
77 * Whether this database connection supports transactional DDL.
79 * Set to FALSE by default because few databases support this feature.
83 protected $transactionalDDLSupport = FALSE;
86 * An index used to generate unique temporary table names.
90 protected $temporaryNameIndex = 0;
93 * The actual PDO connection.
97 protected $connection;
100 * The connection information for this connection object.
104 protected $connectionOptions = [];
107 * The schema object for this connection.
109 * Set to NULL when the schema is destroyed.
111 * @var \Drupal\Core\Database\Schema|null
113 protected $schema = NULL;
116 * The prefixes used by this database connection.
120 protected $prefixes = [];
123 * List of search values for use in prefixTables().
127 protected $prefixSearch = [];
130 * List of replacement values for use in prefixTables().
134 protected $prefixReplace = [];
137 * List of un-prefixed table names, keyed by prefixed table names.
141 protected $unprefixedTablesMap = [];
144 * List of escaped database, table, and field names, keyed by unescaped names.
148 protected $escapedNames = [];
151 * List of escaped aliases names, keyed by unescaped aliases.
155 protected $escapedAliases = [];
158 * Constructs a Connection object.
160 * @param \PDO $connection
161 * An object of the PDO class representing a database connection.
162 * @param array $connection_options
163 * An array of options for the connection. May include the following:
166 * - Other driver-specific options.
168 public function __construct(\PDO $connection, array $connection_options) {
169 // Initialize and prepare the connection prefix.
170 $this->setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : '');
172 // Set a Statement class, unless the driver opted out.
173 if (!empty($this->statementClass)) {
174 $connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]);
177 $this->connection = $connection;
178 $this->connectionOptions = $connection_options;
182 * Opens a PDO connection.
184 * @param array $connection_options
185 * The database connection settings array.
190 public static function open(array &$connection_options = []) { }
193 * Destroys this Connection object.
195 * PHP does not destruct an object if it is still referenced in other
196 * variables. In case of PDO database connection objects, PHP only closes the
197 * connection when the PDO object is destructed, so any references to this
198 * object may cause the number of maximum allowed connections to be exceeded.
200 public function destroy() {
201 // Destroy all references to this connection by setting them to NULL.
202 // The Statement class attribute only accepts a new value that presents a
203 // proper callable, so we reset it to PDOStatement.
204 if (!empty($this->statementClass)) {
205 $this->connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['PDOStatement', []]);
207 $this->schema = NULL;
211 * Returns the default query options for any given query.
213 * A given query can be customized with a number of option flags in an
215 * - target: The database "target" against which to execute a query. Valid
216 * values are "default" or "replica". The system will first try to open a
217 * connection to a database specified with the user-supplied key. If one
218 * is not available, it will silently fall back to the "default" target.
219 * If multiple databases connections are specified with the same target,
220 * one will be selected at random for the duration of the request.
221 * - fetch: This element controls how rows from a result set will be
222 * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
223 * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
224 * class. If a string is specified, each record will be fetched into a new
225 * object of that class. The behavior of all other values is defined by PDO.
226 * See http://php.net/manual/pdostatement.fetch.php
227 * - return: Depending on the type of query, different return values may be
228 * meaningful. This directive instructs the system which type of return
229 * value is desired. The system will generally set the correct value
230 * automatically, so it is extremely rare that a module developer will ever
231 * need to specify this value. Setting it incorrectly will likely lead to
232 * unpredictable results or fatal errors. Legal values include:
233 * - Database::RETURN_STATEMENT: Return the prepared statement object for
234 * the query. This is usually only meaningful for SELECT queries, where
235 * the statement object is how one accesses the result set returned by the
237 * - Database::RETURN_AFFECTED: Return the number of rows affected by an
238 * UPDATE or DELETE query. Be aware that means the number of rows actually
239 * changed, not the number of rows matched by the WHERE clause.
240 * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
241 * created by an INSERT statement on a table that contains a serial
243 * - Database::RETURN_NULL: Do not return anything, as there is no
244 * meaningful value to return. That is the case for INSERT queries on
245 * tables that do not contain a serial column.
246 * - throw_exception: By default, the database system will catch any errors
247 * on a query as an Exception, log it, and then rethrow it so that code
248 * further up the call chain can take an appropriate action. To suppress
249 * that behavior and simply return NULL on failure, set this option to
251 * - allow_delimiter_in_query: By default, queries which have the ; delimiter
252 * any place in them will cause an exception. This reduces the chance of SQL
253 * injection attacks that terminate the original query and add one or more
254 * additional queries (such as inserting new user accounts). In rare cases,
255 * such as creating an SQL function, a ; is needed and can be allowed by
256 * changing this option to TRUE.
259 * An array of default query options.
261 protected function defaultOptions() {
263 'target' => 'default',
264 'fetch' => \PDO::FETCH_OBJ,
265 'return' => Database::RETURN_STATEMENT,
266 'throw_exception' => TRUE,
267 'allow_delimiter_in_query' => FALSE,
272 * Returns the connection information for this connection object.
274 * Note that Database::getConnectionInfo() is for requesting information
275 * about an arbitrary database connection that is defined. This method
276 * is for requesting the connection information of this specific
277 * open connection object.
280 * An array of the connection information. The exact list of
281 * properties is driver-dependent.
283 public function getConnectionOptions() {
284 return $this->connectionOptions;
288 * Set the list of prefixes used by this database connection.
290 * @param array|string $prefix
291 * Either a single prefix, or an array of prefixes, in any of the multiple
292 * forms documented in default.settings.php.
294 protected function setPrefix($prefix) {
295 if (is_array($prefix)) {
296 $this->prefixes = $prefix + ['default' => ''];
299 $this->prefixes = ['default' => $prefix];
302 // Set up variables for use in prefixTables(). Replace table-specific
304 $this->prefixSearch = [];
305 $this->prefixReplace = [];
306 foreach ($this->prefixes as $key => $val) {
307 if ($key != 'default') {
308 $this->prefixSearch[] = '{' . $key . '}';
309 $this->prefixReplace[] = $val . $key;
312 // Then replace remaining tables with the default prefix.
313 $this->prefixSearch[] = '{';
314 $this->prefixReplace[] = $this->prefixes['default'];
315 $this->prefixSearch[] = '}';
316 $this->prefixReplace[] = '';
318 // Set up a map of prefixed => un-prefixed tables.
319 foreach ($this->prefixes as $table_name => $prefix) {
320 if ($table_name !== 'default') {
321 $this->unprefixedTablesMap[$prefix . $table_name] = $table_name;
327 * Appends a database prefix to all tables in a query.
329 * Queries sent to Drupal should wrap all table names in curly brackets. This
330 * function searches for this syntax and adds Drupal's table prefix to all
331 * tables, allowing Drupal to coexist with other systems in the same database
332 * and/or schema if necessary.
335 * A string containing a partial or entire SQL query.
338 * The properly-prefixed string.
340 public function prefixTables($sql) {
341 return str_replace($this->prefixSearch, $this->prefixReplace, $sql);
345 * Find the prefix for a table.
347 * This function is for when you want to know the prefix of a table. This
348 * is not used in prefixTables due to performance reasons.
350 * @param string $table
351 * (optional) The table to find the prefix for.
353 public function tablePrefix($table = 'default') {
354 if (isset($this->prefixes[$table])) {
355 return $this->prefixes[$table];
358 return $this->prefixes['default'];
363 * Gets a list of individually prefixed table names.
366 * An array of un-prefixed table names, keyed by their fully qualified table
367 * names (i.e. prefix + table_name).
369 public function getUnprefixedTablesMap() {
370 return $this->unprefixedTablesMap;
374 * Get a fully qualified table name.
376 * @param string $table
377 * The name of the table in question.
381 public function getFullQualifiedTableName($table) {
382 $options = $this->getConnectionOptions();
383 $prefix = $this->tablePrefix($table);
384 return $options['database'] . '.' . $prefix . $table;
388 * Prepares a query string and returns the prepared statement.
390 * This method caches prepared statements, reusing them when
391 * possible. It also prefixes tables names enclosed in curly-braces.
394 * The query string as SQL, with curly-braces surrounding the
397 * @return \Drupal\Core\Database\StatementInterface
398 * A PDO prepared statement ready for its execute() method.
400 public function prepareQuery($query) {
401 $query = $this->prefixTables($query);
403 return $this->connection->prepare($query);
407 * Tells this connection object what its target value is.
409 * This is needed for logging and auditing. It's sloppy to do in the
410 * constructor because the constructor for child classes has a different
411 * signature. We therefore also ensure that this function is only ever
414 * @param string $target
415 * (optional) The target this connection is for.
417 public function setTarget($target = NULL) {
418 if (!isset($this->target)) {
419 $this->target = $target;
424 * Returns the target this connection is associated with.
426 * @return string|null
427 * The target string of this connection, or NULL if no target is set.
429 public function getTarget() {
430 return $this->target;
434 * Tells this connection object what its key is.
437 * The key this connection is for.
439 public function setKey($key) {
440 if (!isset($this->key)) {
446 * Returns the key this connection is associated with.
448 * @return string|null
449 * The key of this connection, or NULL if no key is set.
451 public function getKey() {
456 * Associates a logging object with this connection.
458 * @param \Drupal\Core\Database\Log $logger
459 * The logging object we want to use.
461 public function setLogger(Log $logger) {
462 $this->logger = $logger;
466 * Gets the current logging object for this connection.
468 * @return \Drupal\Core\Database\Log|null
469 * The current logging object for this connection. If there isn't one,
472 public function getLogger() {
473 return $this->logger;
477 * Creates the appropriate sequence name for a given table and serial field.
479 * This information is exposed to all database drivers, although it is only
480 * useful on some of them. This method is table prefix-aware.
482 * @param string $table
483 * The table name to use for the sequence.
484 * @param string $field
485 * The field name to use for the sequence.
488 * A table prefix-parsed string for the sequence name.
490 public function makeSequenceName($table, $field) {
491 return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
495 * Flatten an array of query comments into a single comment string.
497 * The comment string will be sanitized to avoid SQL injection attacks.
499 * @param string[] $comments
500 * An array of query comment strings.
503 * A sanitized comment string.
505 public function makeComment($comments) {
506 if (empty($comments))
509 // Flatten the array of comments.
510 $comment = implode('. ', $comments);
512 // Sanitize the comment string so as to avoid SQL injection attacks.
513 return '/* ' . $this->filterComment($comment) . ' */ ';
517 * Sanitize a query comment string.
519 * Ensure a query comment does not include strings such as "* /" that might
520 * terminate the comment early. This avoids SQL injection attacks via the
521 * query comment. The comment strings in this example are separated by a
522 * space to avoid PHP parse errors.
524 * For example, the comment:
526 * db_update('example')
527 * ->condition('id', $id)
528 * ->fields(array('field2' => 10))
529 * ->comment('Exploit * / DROP TABLE node; --')
533 * Would result in the following SQL statement being generated:
535 * "/ * Exploit * / DROP TABLE node. -- * / UPDATE example SET field2=..."
538 * Unless the comment is sanitised first, the SQL server would drop the
539 * node table and ignore the rest of the SQL statement.
541 * @param string $comment
542 * A query comment string.
545 * A sanitized version of the query comment string.
547 protected function filterComment($comment = '') {
548 // Change semicolons to period to avoid triggering multi-statement check.
549 return strtr($comment, ['*' => ' * ', ';' => '.']);
553 * Executes a query string against the database.
555 * This method provides a central handler for the actual execution of every
556 * query. All queries executed by Drupal are executed as PDO prepared
559 * @param string|\Drupal\Core\Database\StatementInterface $query
560 * The query to execute. In most cases this will be a string containing
561 * an SQL query with placeholders. An already-prepared instance of
562 * StatementInterface may also be passed in order to allow calling
563 * code to manually bind variables to a query. If a
564 * StatementInterface is passed, the $args array will be ignored.
565 * It is extremely rare that module code will need to pass a statement
566 * object to this method. It is used primarily for database drivers for
567 * databases that require special LOB field handling.
569 * An array of arguments for the prepared statement. If the prepared
570 * statement uses ? placeholders, this array must be an indexed array.
571 * If it contains named placeholders, it must be an associative array.
572 * @param array $options
573 * An associative array of options to control how the query is run. The
574 * given options will be merged with self::defaultOptions(). See the
575 * documentation for self::defaultOptions() for details.
576 * Typically, $options['return'] will be set by a default or by a query
577 * builder, and should not be set by a user.
579 * @return \Drupal\Core\Database\StatementInterface|int|null
580 * This method will return one of the following:
581 * - If either $options['return'] === self::RETURN_STATEMENT, or
582 * $options['return'] is not set (due to self::defaultOptions()),
583 * returns the executed statement.
584 * - If $options['return'] === self::RETURN_AFFECTED,
585 * returns the number of rows affected by the query
586 * (not the number matched).
587 * - If $options['return'] === self::RETURN_INSERT_ID,
588 * returns the generated insert ID of the last query.
589 * - If either $options['return'] === self::RETURN_NULL, or
590 * an exception occurs and $options['throw_exception'] evaluates to FALSE,
593 * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
594 * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
595 * @throws \InvalidArgumentException
597 * @see \Drupal\Core\Database\Connection::defaultOptions()
599 public function query($query, array $args = [], $options = []) {
600 // Use default values if not already set.
601 $options += $this->defaultOptions();
604 // We allow either a pre-bound statement object or a literal string.
605 // In either case, we want to end up with an executed statement object,
606 // which we pass to PDOStatement::execute.
607 if ($query instanceof StatementInterface) {
609 $stmt->execute(NULL, $options);
612 $this->expandArguments($query, $args);
613 // To protect against SQL injection, Drupal only supports executing one
614 // statement at a time. Thus, the presence of a SQL delimiter (the
615 // semicolon) is not allowed unless the option is set. Allowing
616 // semicolons should only be needed for special cases like defining a
617 // function or stored procedure in SQL. Trim any trailing delimiter to
618 // minimize false positives.
619 $query = rtrim($query, "; \t\n\r\0\x0B");
620 if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) {
621 throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.');
623 $stmt = $this->prepareQuery($query);
624 $stmt->execute($args, $options);
627 // Depending on the type of query we may need to return a different value.
628 // See DatabaseConnection::defaultOptions() for a description of each
630 switch ($options['return']) {
631 case Database::RETURN_STATEMENT:
633 case Database::RETURN_AFFECTED:
634 $stmt->allowRowCount = TRUE;
635 return $stmt->rowCount();
636 case Database::RETURN_INSERT_ID:
637 $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL;
638 return $this->connection->lastInsertId($sequence_name);
639 case Database::RETURN_NULL:
642 throw new \PDOException('Invalid return directive: ' . $options['return']);
645 catch (\PDOException $e) {
646 // Most database drivers will return NULL here, but some of them
647 // (e.g. the SQLite driver) may need to re-run the query, so the return
648 // value will be the same as for static::query().
649 return $this->handleQueryException($e, $query, $args, $options);
654 * Wraps and re-throws any PDO exception thrown by static::query().
656 * @param \PDOException $e
657 * The exception thrown by static::query().
659 * The query executed by static::query().
661 * An array of arguments for the prepared statement.
662 * @param array $options
663 * An associative array of options to control how the query is run.
665 * @return \Drupal\Core\Database\StatementInterface|int|null
666 * Most database drivers will return NULL when a PDO exception is thrown for
667 * a query, but some of them may need to re-run the query, so they can also
668 * return a \Drupal\Core\Database\StatementInterface object or an integer.
670 * @throws \Drupal\Core\Database\DatabaseExceptionWrapper
671 * @throws \Drupal\Core\Database\IntegrityConstraintViolationException
673 protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) {
674 if ($options['throw_exception']) {
675 // Wrap the exception in another exception, because PHP does not allow
676 // overriding Exception::getMessage(). Its message is the extra database
677 // debug information.
678 $query_string = ($query instanceof StatementInterface) ? $query->getQueryString() : $query;
679 $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE);
680 // Match all SQLSTATE 23xxx errors.
681 if (substr($e->getCode(), -6, -3) == '23') {
682 $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e);
685 $exception = new DatabaseExceptionWrapper($message, 0, $e);
695 * Expands out shorthand placeholders.
697 * Drupal supports an alternate syntax for doing arrays of values. We
698 * therefore need to expand them out into a full, executable query string.
700 * @param string $query
701 * The query string to modify.
703 * The arguments for the query.
706 * TRUE if the query was modified, FALSE otherwise.
708 * @throws \InvalidArgumentException
709 * This exception is thrown when:
710 * - A placeholder that ends in [] is supplied, and the supplied value is
712 * - A placeholder that does not end in [] is supplied, and the supplied
715 protected function expandArguments(&$query, &$args) {
718 // If the placeholder indicated the value to use is an array, we need to
719 // expand it out into a comma-delimited set of placeholders.
720 foreach ($args as $key => $data) {
721 $is_bracket_placeholder = substr($key, -2) === '[]';
722 $is_array_data = is_array($data);
723 if ($is_bracket_placeholder && !$is_array_data) {
724 throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.');
726 elseif (!$is_bracket_placeholder) {
727 if ($is_array_data) {
728 throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.');
730 // Scalar placeholder - does not need to be expanded.
733 // Handle expansion of arrays.
734 $key_name = str_replace('[]', '__', $key);
736 // We require placeholders to have trailing brackets if the developer
737 // intends them to be expanded to an array to make the intent explicit.
738 foreach (array_values($data) as $i => $value) {
739 // This assumes that there are no other placeholders that use the same
740 // name. For example, if the array placeholder is defined as :example[]
741 // and there is already an :example_2 placeholder, this will generate
742 // a duplicate key. We do not account for that as the calling code
743 // is already broken if that happens.
744 $new_keys[$key_name . $i] = $value;
747 // Update the query with the new placeholders.
748 $query = str_replace($key, implode(', ', array_keys($new_keys)), $query);
750 // Update the args array with the new placeholders.
761 * Gets the driver-specific override class if any for the specified class.
763 * @param string $class
764 * The class for which we want the potentially driver-specific class.
766 * The name of the class that should be used for this driver.
768 public function getDriverClass($class) {
769 if (empty($this->driverClasses[$class])) {
770 if (empty($this->connectionOptions['namespace'])) {
771 // Fallback for Drupal 7 settings.php and the test runner script.
772 $this->connectionOptions['namespace'] = (new \ReflectionObject($this))->getNamespaceName();
774 $driver_class = $this->connectionOptions['namespace'] . '\\' . $class;
775 $this->driverClasses[$class] = class_exists($driver_class) ? $driver_class : $class;
777 return $this->driverClasses[$class];
781 * Prepares and returns a SELECT query object.
783 * @param string $table
784 * The base table for this query, that is, the first table in the FROM
785 * clause. This table will also be used as the "base" table for query_alter
786 * hook implementations.
787 * @param string $alias
788 * (optional) The alias of the base table of this query.
790 * An array of options on the query.
792 * @return \Drupal\Core\Database\Query\SelectInterface
793 * An appropriate SelectQuery object for this database connection. Note that
794 * it may be a driver-specific subclass of SelectQuery, depending on the
797 * @see \Drupal\Core\Database\Query\Select
799 public function select($table, $alias = NULL, array $options = []) {
800 $class = $this->getDriverClass('Select');
801 return new $class($table, $alias, $this, $options);
805 * Prepares and returns an INSERT query object.
807 * @param string $table
808 * The table to use for the insert statement.
809 * @param array $options
810 * (optional) An array of options on the query.
812 * @return \Drupal\Core\Database\Query\Insert
813 * A new Insert query object.
815 * @see \Drupal\Core\Database\Query\Insert
817 public function insert($table, array $options = []) {
818 $class = $this->getDriverClass('Insert');
819 return new $class($this, $table, $options);
823 * Prepares and returns a MERGE query object.
825 * @param string $table
826 * The table to use for the merge statement.
827 * @param array $options
828 * (optional) An array of options on the query.
830 * @return \Drupal\Core\Database\Query\Merge
831 * A new Merge query object.
833 * @see \Drupal\Core\Database\Query\Merge
835 public function merge($table, array $options = []) {
836 $class = $this->getDriverClass('Merge');
837 return new $class($this, $table, $options);
841 * Prepares and returns an UPSERT query object.
843 * @param string $table
844 * The table to use for the upsert query.
845 * @param array $options
846 * (optional) An array of options on the query.
848 * @return \Drupal\Core\Database\Query\Upsert
849 * A new Upsert query object.
851 * @see \Drupal\Core\Database\Query\Upsert
853 public function upsert($table, array $options = []) {
854 $class = $this->getDriverClass('Upsert');
855 return new $class($this, $table, $options);
859 * Prepares and returns an UPDATE query object.
861 * @param string $table
862 * The table to use for the update statement.
863 * @param array $options
864 * (optional) An array of options on the query.
866 * @return \Drupal\Core\Database\Query\Update
867 * A new Update query object.
869 * @see \Drupal\Core\Database\Query\Update
871 public function update($table, array $options = []) {
872 $class = $this->getDriverClass('Update');
873 return new $class($this, $table, $options);
877 * Prepares and returns a DELETE query object.
879 * @param string $table
880 * The table to use for the delete statement.
881 * @param array $options
882 * (optional) An array of options on the query.
884 * @return \Drupal\Core\Database\Query\Delete
885 * A new Delete query object.
887 * @see \Drupal\Core\Database\Query\Delete
889 public function delete($table, array $options = []) {
890 $class = $this->getDriverClass('Delete');
891 return new $class($this, $table, $options);
895 * Prepares and returns a TRUNCATE query object.
897 * @param string $table
898 * The table to use for the truncate statement.
899 * @param array $options
900 * (optional) An array of options on the query.
902 * @return \Drupal\Core\Database\Query\Truncate
903 * A new Truncate query object.
905 * @see \Drupal\Core\Database\Query\Truncate
907 public function truncate($table, array $options = []) {
908 $class = $this->getDriverClass('Truncate');
909 return new $class($this, $table, $options);
913 * Returns a DatabaseSchema object for manipulating the schema.
915 * This method will lazy-load the appropriate schema library file.
917 * @return \Drupal\Core\Database\Schema
918 * The database Schema object for this connection.
920 public function schema() {
921 if (empty($this->schema)) {
922 $class = $this->getDriverClass('Schema');
923 $this->schema = new $class($this);
925 return $this->schema;
929 * Escapes a database name string.
931 * Force all database names to be strictly alphanumeric-plus-underscore.
932 * For some database drivers, it may also wrap the database name in
933 * database-specific escape characters.
935 * @param string $database
936 * An unsanitized database name.
939 * The sanitized database name.
941 public function escapeDatabase($database) {
942 if (!isset($this->escapedNames[$database])) {
943 $this->escapedNames[$database] = preg_replace('/[^A-Za-z0-9_.]+/', '', $database);
945 return $this->escapedNames[$database];
949 * Escapes a table name string.
951 * Force all table names to be strictly alphanumeric-plus-underscore.
952 * For some database drivers, it may also wrap the table name in
953 * database-specific escape characters.
955 * @param string $table
956 * An unsanitized table name.
959 * The sanitized table name.
961 public function escapeTable($table) {
962 if (!isset($this->escapedNames[$table])) {
963 $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
965 return $this->escapedNames[$table];
969 * Escapes a field name string.
971 * Force all field names to be strictly alphanumeric-plus-underscore.
972 * For some database drivers, it may also wrap the field name in
973 * database-specific escape characters.
975 * @param string $field
976 * An unsanitized field name.
979 * The sanitized field name.
981 public function escapeField($field) {
982 if (!isset($this->escapedNames[$field])) {
983 $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
985 return $this->escapedNames[$field];
989 * Escapes an alias name string.
991 * Force all alias names to be strictly alphanumeric-plus-underscore. In
992 * contrast to DatabaseConnection::escapeField() /
993 * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
994 * because that is not allowed in aliases.
996 * @param string $field
997 * An unsanitized alias name.
1000 * The sanitized alias name.
1002 public function escapeAlias($field) {
1003 if (!isset($this->escapedAliases[$field])) {
1004 $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
1006 return $this->escapedAliases[$field];
1010 * Escapes characters that work as wildcard characters in a LIKE pattern.
1012 * The wildcard characters "%" and "_" as well as backslash are prefixed with
1013 * a backslash. Use this to do a search for a verbatim string without any
1014 * wildcard behavior.
1016 * For example, the following does a case-insensitive query for all rows whose
1017 * name starts with $prefix:
1019 * $result = db_query(
1020 * 'SELECT * FROM person WHERE name LIKE :pattern',
1021 * array(':pattern' => db_like($prefix) . '%')
1025 * Backslash is defined as escape character for LIKE patterns in
1026 * Drupal\Core\Database\Query\Condition::mapConditionOperator().
1028 * @param string $string
1029 * The string to escape.
1032 * The escaped string.
1034 public function escapeLike($string) {
1035 return addcslashes($string, '\%_');
1039 * Determines if there is an active transaction open.
1042 * TRUE if we're currently in a transaction, FALSE otherwise.
1044 public function inTransaction() {
1045 return ($this->transactionDepth() > 0);
1049 * Determines the current transaction depth.
1052 * The current transaction depth.
1054 public function transactionDepth() {
1055 return count($this->transactionLayers);
1059 * Returns a new DatabaseTransaction object on this connection.
1061 * @param string $name
1062 * (optional) The name of the savepoint.
1064 * @return \Drupal\Core\Database\Transaction
1065 * A Transaction object.
1067 * @see \Drupal\Core\Database\Transaction
1069 public function startTransaction($name = '') {
1070 $class = $this->getDriverClass('Transaction');
1071 return new $class($this, $name);
1075 * Rolls back the transaction entirely or to a named savepoint.
1077 * This method throws an exception if no transaction is active.
1079 * @param string $savepoint_name
1080 * (optional) The name of the savepoint. The default, 'drupal_transaction',
1081 * will roll the entire transaction back.
1083 * @throws \Drupal\Core\Database\TransactionOutOfOrderException
1084 * @throws \Drupal\Core\Database\TransactionNoActiveException
1086 * @see \Drupal\Core\Database\Transaction::rollBack()
1088 public function rollBack($savepoint_name = 'drupal_transaction') {
1089 if (!$this->supportsTransactions()) {
1092 if (!$this->inTransaction()) {
1093 throw new TransactionNoActiveException();
1095 // A previous rollback to an earlier savepoint may mean that the savepoint
1096 // in question has already been accidentally committed.
1097 if (!isset($this->transactionLayers[$savepoint_name])) {
1098 throw new TransactionNoActiveException();
1101 // We need to find the point we're rolling back to, all other savepoints
1102 // before are no longer needed. If we rolled back other active savepoints,
1103 // we need to throw an exception.
1104 $rolled_back_other_active_savepoints = FALSE;
1105 while ($savepoint = array_pop($this->transactionLayers)) {
1106 if ($savepoint == $savepoint_name) {
1107 // If it is the last the transaction in the stack, then it is not a
1108 // savepoint, it is the transaction itself so we will need to roll back
1109 // the transaction rather than a savepoint.
1110 if (empty($this->transactionLayers)) {
1113 $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
1114 $this->popCommittableTransactions();
1115 if ($rolled_back_other_active_savepoints) {
1116 throw new TransactionOutOfOrderException();
1121 $rolled_back_other_active_savepoints = TRUE;
1124 $this->connection->rollBack();
1125 if ($rolled_back_other_active_savepoints) {
1126 throw new TransactionOutOfOrderException();
1131 * Increases the depth of transaction nesting.
1133 * If no transaction is already active, we begin a new transaction.
1135 * @param string $name
1136 * The name of the transaction.
1138 * @throws \Drupal\Core\Database\TransactionNameNonUniqueException
1140 * @see \Drupal\Core\Database\Transaction
1142 public function pushTransaction($name) {
1143 if (!$this->supportsTransactions()) {
1146 if (isset($this->transactionLayers[$name])) {
1147 throw new TransactionNameNonUniqueException($name . " is already in use.");
1149 // If we're already in a transaction then we want to create a savepoint
1150 // rather than try to create another transaction.
1151 if ($this->inTransaction()) {
1152 $this->query('SAVEPOINT ' . $name);
1155 $this->connection->beginTransaction();
1157 $this->transactionLayers[$name] = $name;
1161 * Decreases the depth of transaction nesting.
1163 * If we pop off the last transaction layer, then we either commit or roll
1164 * back the transaction as necessary. If no transaction is active, we return
1165 * because the transaction may have manually been rolled back.
1167 * @param string $name
1168 * The name of the savepoint.
1170 * @throws \Drupal\Core\Database\TransactionNoActiveException
1171 * @throws \Drupal\Core\Database\TransactionCommitFailedException
1173 * @see \Drupal\Core\Database\Transaction
1175 public function popTransaction($name) {
1176 if (!$this->supportsTransactions()) {
1179 // The transaction has already been committed earlier. There is nothing we
1180 // need to do. If this transaction was part of an earlier out-of-order
1181 // rollback, an exception would already have been thrown by
1182 // Database::rollBack().
1183 if (!isset($this->transactionLayers[$name])) {
1187 // Mark this layer as committable.
1188 $this->transactionLayers[$name] = FALSE;
1189 $this->popCommittableTransactions();
1193 * Internal function: commit all the transaction layers that can commit.
1195 protected function popCommittableTransactions() {
1196 // Commit all the committable layers.
1197 foreach (array_reverse($this->transactionLayers) as $name => $active) {
1198 // Stop once we found an active transaction.
1203 // If there are no more layers left then we should commit.
1204 unset($this->transactionLayers[$name]);
1205 if (empty($this->transactionLayers)) {
1206 if (!$this->connection->commit()) {
1207 throw new TransactionCommitFailedException();
1211 $this->query('RELEASE SAVEPOINT ' . $name);
1217 * Runs a limited-range query on this database object.
1219 * Use this as a substitute for ->query() when a subset of the query is to be
1220 * returned. User-supplied arguments to the query should be passed in as
1221 * separate parameters so that they can be properly escaped to avoid SQL
1222 * injection attacks.
1224 * @param string $query
1225 * A string containing an SQL query.
1227 * The first result row to return.
1229 * The maximum number of result rows to return.
1230 * @param array $args
1231 * (optional) An array of values to substitute into the query at placeholder
1233 * @param array $options
1234 * (optional) An array of options on the query.
1236 * @return \Drupal\Core\Database\StatementInterface
1237 * A database query result resource, or NULL if the query was not executed
1240 abstract public function queryRange($query, $from, $count, array $args = [], array $options = []);
1243 * Generates a temporary table name.
1248 protected function generateTemporaryTableName() {
1249 return "db_temporary_" . $this->temporaryNameIndex++;
1253 * Runs a SELECT query and stores its results in a temporary table.
1255 * Use this as a substitute for ->query() when the results need to stored
1256 * in a temporary table. Temporary tables exist for the duration of the page
1257 * request. User-supplied arguments to the query should be passed in as
1258 * separate parameters so that they can be properly escaped to avoid SQL
1259 * injection attacks.
1261 * Note that if you need to know how many results were returned, you should do
1262 * a SELECT COUNT(*) on the temporary table afterwards.
1264 * @param string $query
1265 * A string containing a normal SELECT SQL query.
1266 * @param array $args
1267 * (optional) An array of values to substitute into the query at placeholder
1269 * @param array $options
1270 * (optional) An associative array of options to control how the query is
1271 * run. See the documentation for DatabaseConnection::defaultOptions() for
1275 * The name of the temporary table.
1277 abstract public function queryTemporary($query, array $args = [], array $options = []);
1280 * Returns the type of database driver.
1282 * This is not necessarily the same as the type of the database itself. For
1283 * instance, there could be two MySQL drivers, mysql and mysql_mock. This
1284 * function would return different values for each, but both would return
1285 * "mysql" for databaseType().
1288 * The type of database driver.
1290 abstract public function driver();
1293 * Returns the version of the database server.
1295 public function version() {
1296 return $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION);
1300 * Returns the version of the database client.
1302 public function clientVersion() {
1303 return $this->connection->getAttribute(\PDO::ATTR_CLIENT_VERSION);
1307 * Determines if this driver supports transactions.
1310 * TRUE if this connection supports transactions, FALSE otherwise.
1312 public function supportsTransactions() {
1313 return $this->transactionSupport;
1317 * Determines if this driver supports transactional DDL.
1319 * DDL queries are those that change the schema, such as ALTER queries.
1322 * TRUE if this connection supports transactions for DDL queries, FALSE
1325 public function supportsTransactionalDDL() {
1326 return $this->transactionalDDLSupport;
1330 * Returns the name of the PDO driver for this connection.
1332 abstract public function databaseType();
1335 * Creates a database.
1337 * In order to use this method, you must be connected without a database
1340 * @param string $database
1341 * The name of the database to create.
1343 abstract public function createDatabase($database);
1346 * Gets any special processing requirements for the condition operator.
1348 * Some condition types require special processing, such as IN, because
1349 * the value data they pass in is not a simple value. This is a simple
1350 * overridable lookup function. Database connections should define only
1351 * those operators they wish to be handled differently than the default.
1353 * @param string $operator
1354 * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
1357 * The extra handling directives for the specified operator, or NULL.
1359 * @see \Drupal\Core\Database\Query\Condition::compile()
1361 abstract public function mapConditionOperator($operator);
1364 * Throws an exception to deny direct access to transaction commits.
1366 * We do not want to allow users to commit transactions at any time, only
1367 * by destroying the transaction object or allowing it to go out of scope.
1368 * A direct commit bypasses all of the safety checks we've built on top of
1369 * PDO's transaction routines.
1371 * @throws \Drupal\Core\Database\TransactionExplicitCommitNotAllowedException
1373 * @see \Drupal\Core\Database\Transaction
1375 public function commit() {
1376 throw new TransactionExplicitCommitNotAllowedException();
1380 * Retrieves an unique ID from a given sequence.
1382 * Use this function if for some reason you can't use a serial field. For
1383 * example, MySQL has no ways of reading of the current value of a sequence
1384 * and PostgreSQL can not advance the sequence to be larger than a given
1385 * value. Or sometimes you just need a unique integer.
1387 * @param $existing_id
1388 * (optional) After a database import, it might be that the sequences table
1389 * is behind, so by passing in the maximum existing ID, it can be assured
1390 * that we never issue the same ID.
1393 * An integer number larger than any number returned by earlier calls and
1394 * also larger than the $existing_id if one was passed in.
1396 abstract public function nextId($existing_id = 0);
1399 * Prepares a statement for execution and returns a statement object
1401 * Emulated prepared statements does not communicate with the database server
1402 * so this method does not check the statement.
1404 * @param string $statement
1405 * This must be a valid SQL statement for the target database server.
1406 * @param array $driver_options
1407 * (optional) This array holds one or more key=>value pairs to set
1408 * attribute values for the PDOStatement object that this method returns.
1409 * You would most commonly use this to set the \PDO::ATTR_CURSOR value to
1410 * \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have
1411 * driver specific options that may be set at prepare-time. Defaults to an
1414 * @return \PDOStatement|false
1415 * If the database server successfully prepares the statement, returns a
1416 * \PDOStatement object.
1417 * If the database server cannot successfully prepare the statement returns
1418 * FALSE or emits \PDOException (depending on error handling).
1420 * @throws \PDOException
1422 * @see \PDO::prepare()
1424 public function prepare($statement, array $driver_options = []) {
1425 return $this->connection->prepare($statement, $driver_options);
1429 * Quotes a string for use in a query.
1431 * @param string $string
1432 * The string to be quoted.
1433 * @param int $parameter_type
1434 * (optional) Provides a data type hint for drivers that have alternate
1435 * quoting styles. Defaults to \PDO::PARAM_STR.
1437 * @return string|bool
1438 * A quoted string that is theoretically safe to pass into an SQL statement.
1439 * Returns FALSE if the driver does not support quoting in this way.
1441 * @see \PDO::quote()
1443 public function quote($string, $parameter_type = \PDO::PARAM_STR) {
1444 return $this->connection->quote($string, $parameter_type);
1448 * Extracts the SQLSTATE error from the PDOException.
1450 * @param \Exception $e
1454 * The five character error code.
1456 protected static function getSQLState(\Exception $e) {
1457 // The PDOException code is not always reliable, try to see whether the
1458 // message has something usable.
1459 if (preg_match('/^SQLSTATE\[(\w{5})\]/', $e->getMessage(), $matches)) {
1463 return $e->getCode();
1468 * Prevents the database connection from being serialized.
1470 public function __sleep() {
1471 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.');