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