Chris@0: setPrefix(isset($connection_options['prefix']) ? $connection_options['prefix'] : ''); Chris@0: Chris@0: // Set a Statement class, unless the driver opted out. Chris@0: if (!empty($this->statementClass)) { Chris@0: $connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [$this->statementClass, [$this]]); Chris@0: } Chris@0: Chris@0: $this->connection = $connection; Chris@0: $this->connectionOptions = $connection_options; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Opens a PDO connection. Chris@0: * Chris@0: * @param array $connection_options Chris@0: * The database connection settings array. Chris@0: * Chris@0: * @return \PDO Chris@0: * A \PDO object. Chris@0: */ Chris@0: public static function open(array &$connection_options = []) {} Chris@0: Chris@0: /** Chris@0: * Destroys this Connection object. Chris@0: * Chris@0: * PHP does not destruct an object if it is still referenced in other Chris@0: * variables. In case of PDO database connection objects, PHP only closes the Chris@0: * connection when the PDO object is destructed, so any references to this Chris@0: * object may cause the number of maximum allowed connections to be exceeded. Chris@0: */ Chris@0: public function destroy() { Chris@0: // Destroy all references to this connection by setting them to NULL. Chris@0: // The Statement class attribute only accepts a new value that presents a Chris@0: // proper callable, so we reset it to PDOStatement. Chris@0: if (!empty($this->statementClass)) { Chris@0: $this->connection->setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['PDOStatement', []]); Chris@0: } Chris@0: $this->schema = NULL; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the default query options for any given query. Chris@0: * Chris@0: * A given query can be customized with a number of option flags in an Chris@0: * associative array: Chris@0: * - target: The database "target" against which to execute a query. Valid Chris@0: * values are "default" or "replica". The system will first try to open a Chris@0: * connection to a database specified with the user-supplied key. If one Chris@0: * is not available, it will silently fall back to the "default" target. Chris@0: * If multiple databases connections are specified with the same target, Chris@0: * one will be selected at random for the duration of the request. Chris@0: * - fetch: This element controls how rows from a result set will be Chris@0: * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH, Chris@0: * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a Chris@0: * class. If a string is specified, each record will be fetched into a new Chris@0: * object of that class. The behavior of all other values is defined by PDO. Chris@0: * See http://php.net/manual/pdostatement.fetch.php Chris@0: * - return: Depending on the type of query, different return values may be Chris@0: * meaningful. This directive instructs the system which type of return Chris@0: * value is desired. The system will generally set the correct value Chris@0: * automatically, so it is extremely rare that a module developer will ever Chris@0: * need to specify this value. Setting it incorrectly will likely lead to Chris@0: * unpredictable results or fatal errors. Legal values include: Chris@0: * - Database::RETURN_STATEMENT: Return the prepared statement object for Chris@0: * the query. This is usually only meaningful for SELECT queries, where Chris@0: * the statement object is how one accesses the result set returned by the Chris@0: * query. Chris@0: * - Database::RETURN_AFFECTED: Return the number of rows affected by an Chris@0: * UPDATE or DELETE query. Be aware that means the number of rows actually Chris@0: * changed, not the number of rows matched by the WHERE clause. Chris@0: * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key) Chris@0: * created by an INSERT statement on a table that contains a serial Chris@0: * column. Chris@0: * - Database::RETURN_NULL: Do not return anything, as there is no Chris@0: * meaningful value to return. That is the case for INSERT queries on Chris@0: * tables that do not contain a serial column. Chris@0: * - throw_exception: By default, the database system will catch any errors Chris@0: * on a query as an Exception, log it, and then rethrow it so that code Chris@0: * further up the call chain can take an appropriate action. To suppress Chris@0: * that behavior and simply return NULL on failure, set this option to Chris@0: * FALSE. Chris@0: * - allow_delimiter_in_query: By default, queries which have the ; delimiter Chris@0: * any place in them will cause an exception. This reduces the chance of SQL Chris@0: * injection attacks that terminate the original query and add one or more Chris@0: * additional queries (such as inserting new user accounts). In rare cases, Chris@0: * such as creating an SQL function, a ; is needed and can be allowed by Chris@0: * changing this option to TRUE. Chris@0: * Chris@0: * @return array Chris@0: * An array of default query options. Chris@0: */ Chris@0: protected function defaultOptions() { Chris@0: return [ Chris@0: 'target' => 'default', Chris@0: 'fetch' => \PDO::FETCH_OBJ, Chris@0: 'return' => Database::RETURN_STATEMENT, Chris@0: 'throw_exception' => TRUE, Chris@0: 'allow_delimiter_in_query' => FALSE, Chris@0: ]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the connection information for this connection object. Chris@0: * Chris@0: * Note that Database::getConnectionInfo() is for requesting information Chris@0: * about an arbitrary database connection that is defined. This method Chris@0: * is for requesting the connection information of this specific Chris@0: * open connection object. Chris@0: * Chris@0: * @return array Chris@0: * An array of the connection information. The exact list of Chris@0: * properties is driver-dependent. Chris@0: */ Chris@0: public function getConnectionOptions() { Chris@0: return $this->connectionOptions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set the list of prefixes used by this database connection. Chris@0: * Chris@0: * @param array|string $prefix Chris@0: * Either a single prefix, or an array of prefixes, in any of the multiple Chris@0: * forms documented in default.settings.php. Chris@0: */ Chris@0: protected function setPrefix($prefix) { Chris@0: if (is_array($prefix)) { Chris@0: $this->prefixes = $prefix + ['default' => '']; Chris@0: } Chris@0: else { Chris@0: $this->prefixes = ['default' => $prefix]; Chris@0: } Chris@0: Chris@0: // Set up variables for use in prefixTables(). Replace table-specific Chris@0: // prefixes first. Chris@0: $this->prefixSearch = []; Chris@0: $this->prefixReplace = []; Chris@0: foreach ($this->prefixes as $key => $val) { Chris@0: if ($key != 'default') { Chris@0: $this->prefixSearch[] = '{' . $key . '}'; Chris@0: $this->prefixReplace[] = $val . $key; Chris@0: } Chris@0: } Chris@0: // Then replace remaining tables with the default prefix. Chris@0: $this->prefixSearch[] = '{'; Chris@0: $this->prefixReplace[] = $this->prefixes['default']; Chris@0: $this->prefixSearch[] = '}'; Chris@0: $this->prefixReplace[] = ''; Chris@0: Chris@0: // Set up a map of prefixed => un-prefixed tables. Chris@0: foreach ($this->prefixes as $table_name => $prefix) { Chris@0: if ($table_name !== 'default') { Chris@0: $this->unprefixedTablesMap[$prefix . $table_name] = $table_name; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Appends a database prefix to all tables in a query. Chris@0: * Chris@0: * Queries sent to Drupal should wrap all table names in curly brackets. This Chris@0: * function searches for this syntax and adds Drupal's table prefix to all Chris@0: * tables, allowing Drupal to coexist with other systems in the same database Chris@0: * and/or schema if necessary. Chris@0: * Chris@0: * @param string $sql Chris@0: * A string containing a partial or entire SQL query. Chris@0: * Chris@0: * @return string Chris@0: * The properly-prefixed string. Chris@0: */ Chris@0: public function prefixTables($sql) { Chris@0: return str_replace($this->prefixSearch, $this->prefixReplace, $sql); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Find the prefix for a table. Chris@0: * Chris@0: * This function is for when you want to know the prefix of a table. This Chris@0: * is not used in prefixTables due to performance reasons. Chris@0: * Chris@0: * @param string $table Chris@0: * (optional) The table to find the prefix for. Chris@0: */ Chris@0: public function tablePrefix($table = 'default') { Chris@0: if (isset($this->prefixes[$table])) { Chris@0: return $this->prefixes[$table]; Chris@0: } Chris@0: else { Chris@0: return $this->prefixes['default']; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of individually prefixed table names. Chris@0: * Chris@0: * @return array Chris@0: * An array of un-prefixed table names, keyed by their fully qualified table Chris@0: * names (i.e. prefix + table_name). Chris@0: */ Chris@0: public function getUnprefixedTablesMap() { Chris@0: return $this->unprefixedTablesMap; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get a fully qualified table name. Chris@0: * Chris@0: * @param string $table Chris@0: * The name of the table in question. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getFullQualifiedTableName($table) { Chris@0: $options = $this->getConnectionOptions(); Chris@0: $prefix = $this->tablePrefix($table); Chris@0: return $options['database'] . '.' . $prefix . $table; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares a query string and returns the prepared statement. Chris@0: * Chris@0: * This method caches prepared statements, reusing them when Chris@0: * possible. It also prefixes tables names enclosed in curly-braces. Chris@0: * Chris@0: * @param $query Chris@0: * The query string as SQL, with curly-braces surrounding the Chris@0: * table names. Chris@0: * Chris@0: * @return \Drupal\Core\Database\StatementInterface Chris@0: * A PDO prepared statement ready for its execute() method. Chris@0: */ Chris@0: public function prepareQuery($query) { Chris@0: $query = $this->prefixTables($query); Chris@0: Chris@0: return $this->connection->prepare($query); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tells this connection object what its target value is. Chris@0: * Chris@0: * This is needed for logging and auditing. It's sloppy to do in the Chris@0: * constructor because the constructor for child classes has a different Chris@0: * signature. We therefore also ensure that this function is only ever Chris@0: * called once. Chris@0: * Chris@0: * @param string $target Chris@0: * (optional) The target this connection is for. Chris@0: */ Chris@0: public function setTarget($target = NULL) { Chris@0: if (!isset($this->target)) { Chris@0: $this->target = $target; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the target this connection is associated with. Chris@0: * Chris@0: * @return string|null Chris@0: * The target string of this connection, or NULL if no target is set. Chris@0: */ Chris@0: public function getTarget() { Chris@0: return $this->target; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tells this connection object what its key is. Chris@0: * Chris@0: * @param string $key Chris@0: * The key this connection is for. Chris@0: */ Chris@0: public function setKey($key) { Chris@0: if (!isset($this->key)) { Chris@0: $this->key = $key; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the key this connection is associated with. Chris@0: * Chris@0: * @return string|null Chris@0: * The key of this connection, or NULL if no key is set. Chris@0: */ Chris@0: public function getKey() { Chris@0: return $this->key; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Associates a logging object with this connection. Chris@0: * Chris@0: * @param \Drupal\Core\Database\Log $logger Chris@0: * The logging object we want to use. Chris@0: */ Chris@0: public function setLogger(Log $logger) { Chris@0: $this->logger = $logger; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the current logging object for this connection. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Log|null Chris@0: * The current logging object for this connection. If there isn't one, Chris@0: * NULL is returned. Chris@0: */ Chris@0: public function getLogger() { Chris@0: return $this->logger; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates the appropriate sequence name for a given table and serial field. Chris@0: * Chris@0: * This information is exposed to all database drivers, although it is only Chris@0: * useful on some of them. This method is table prefix-aware. Chris@0: * Chris@18: * Note that if a sequence was generated automatically by the database, its Chris@18: * name might not match the one returned by this function. Therefore, in those Chris@18: * cases, it is generally advised to use a database-specific way of retrieving Chris@18: * the name of an auto-created sequence. For example, PostgreSQL provides a Chris@18: * dedicated function for this purpose: pg_get_serial_sequence(). Chris@18: * Chris@0: * @param string $table Chris@0: * The table name to use for the sequence. Chris@0: * @param string $field Chris@0: * The field name to use for the sequence. Chris@0: * Chris@0: * @return string Chris@0: * A table prefix-parsed string for the sequence name. Chris@0: */ Chris@0: public function makeSequenceName($table, $field) { Chris@0: return $this->prefixTables('{' . $table . '}_' . $field . '_seq'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Flatten an array of query comments into a single comment string. Chris@0: * Chris@0: * The comment string will be sanitized to avoid SQL injection attacks. Chris@0: * Chris@0: * @param string[] $comments Chris@0: * An array of query comment strings. Chris@0: * Chris@0: * @return string Chris@0: * A sanitized comment string. Chris@0: */ Chris@0: public function makeComment($comments) { Chris@0: if (empty($comments)) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: // Flatten the array of comments. Chris@0: $comment = implode('. ', $comments); Chris@0: Chris@0: // Sanitize the comment string so as to avoid SQL injection attacks. Chris@0: return '/* ' . $this->filterComment($comment) . ' */ '; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sanitize a query comment string. Chris@0: * Chris@0: * Ensure a query comment does not include strings such as "* /" that might Chris@0: * terminate the comment early. This avoids SQL injection attacks via the Chris@0: * query comment. The comment strings in this example are separated by a Chris@0: * space to avoid PHP parse errors. Chris@0: * Chris@0: * For example, the comment: Chris@0: * @code Chris@18: * \Drupal::database()->update('example') Chris@0: * ->condition('id', $id) Chris@0: * ->fields(array('field2' => 10)) Chris@0: * ->comment('Exploit * / DROP TABLE node; --') Chris@0: * ->execute() Chris@0: * @endcode Chris@0: * Chris@0: * Would result in the following SQL statement being generated: Chris@0: * @code Chris@0: * "/ * Exploit * / DROP TABLE node. -- * / UPDATE example SET field2=..." Chris@0: * @endcode Chris@0: * Chris@0: * Unless the comment is sanitised first, the SQL server would drop the Chris@0: * node table and ignore the rest of the SQL statement. Chris@0: * Chris@0: * @param string $comment Chris@0: * A query comment string. Chris@0: * Chris@0: * @return string Chris@0: * A sanitized version of the query comment string. Chris@0: */ Chris@0: protected function filterComment($comment = '') { Chris@0: // Change semicolons to period to avoid triggering multi-statement check. Chris@0: return strtr($comment, ['*' => ' * ', ';' => '.']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes a query string against the database. Chris@0: * Chris@0: * This method provides a central handler for the actual execution of every Chris@0: * query. All queries executed by Drupal are executed as PDO prepared Chris@0: * statements. Chris@0: * Chris@0: * @param string|\Drupal\Core\Database\StatementInterface $query Chris@0: * The query to execute. In most cases this will be a string containing Chris@0: * an SQL query with placeholders. An already-prepared instance of Chris@0: * StatementInterface may also be passed in order to allow calling Chris@0: * code to manually bind variables to a query. If a Chris@0: * StatementInterface is passed, the $args array will be ignored. Chris@0: * It is extremely rare that module code will need to pass a statement Chris@0: * object to this method. It is used primarily for database drivers for Chris@0: * databases that require special LOB field handling. Chris@0: * @param array $args Chris@0: * An array of arguments for the prepared statement. If the prepared Chris@0: * statement uses ? placeholders, this array must be an indexed array. Chris@0: * If it contains named placeholders, it must be an associative array. Chris@0: * @param array $options Chris@0: * An associative array of options to control how the query is run. The Chris@0: * given options will be merged with self::defaultOptions(). See the Chris@0: * documentation for self::defaultOptions() for details. Chris@0: * Typically, $options['return'] will be set by a default or by a query Chris@0: * builder, and should not be set by a user. Chris@0: * Chris@0: * @return \Drupal\Core\Database\StatementInterface|int|null Chris@0: * This method will return one of the following: Chris@0: * - If either $options['return'] === self::RETURN_STATEMENT, or Chris@0: * $options['return'] is not set (due to self::defaultOptions()), Chris@0: * returns the executed statement. Chris@0: * - If $options['return'] === self::RETURN_AFFECTED, Chris@0: * returns the number of rows affected by the query Chris@0: * (not the number matched). Chris@0: * - If $options['return'] === self::RETURN_INSERT_ID, Chris@0: * returns the generated insert ID of the last query. Chris@0: * - If either $options['return'] === self::RETURN_NULL, or Chris@0: * an exception occurs and $options['throw_exception'] evaluates to FALSE, Chris@0: * returns NULL. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\DatabaseExceptionWrapper Chris@0: * @throws \Drupal\Core\Database\IntegrityConstraintViolationException Chris@0: * @throws \InvalidArgumentException Chris@0: * Chris@0: * @see \Drupal\Core\Database\Connection::defaultOptions() Chris@0: */ Chris@0: public function query($query, array $args = [], $options = []) { Chris@0: // Use default values if not already set. Chris@0: $options += $this->defaultOptions(); Chris@0: Chris@0: try { Chris@0: // We allow either a pre-bound statement object or a literal string. Chris@0: // In either case, we want to end up with an executed statement object, Chris@0: // which we pass to PDOStatement::execute. Chris@0: if ($query instanceof StatementInterface) { Chris@0: $stmt = $query; Chris@0: $stmt->execute(NULL, $options); Chris@0: } Chris@0: else { Chris@0: $this->expandArguments($query, $args); Chris@0: // To protect against SQL injection, Drupal only supports executing one Chris@0: // statement at a time. Thus, the presence of a SQL delimiter (the Chris@0: // semicolon) is not allowed unless the option is set. Allowing Chris@0: // semicolons should only be needed for special cases like defining a Chris@0: // function or stored procedure in SQL. Trim any trailing delimiter to Chris@0: // minimize false positives. Chris@0: $query = rtrim($query, "; \t\n\r\0\x0B"); Chris@0: if (strpos($query, ';') !== FALSE && empty($options['allow_delimiter_in_query'])) { Chris@0: throw new \InvalidArgumentException('; is not supported in SQL strings. Use only one statement at a time.'); Chris@0: } Chris@0: $stmt = $this->prepareQuery($query); Chris@0: $stmt->execute($args, $options); Chris@0: } Chris@0: Chris@0: // Depending on the type of query we may need to return a different value. Chris@0: // See DatabaseConnection::defaultOptions() for a description of each Chris@0: // value. Chris@0: switch ($options['return']) { Chris@0: case Database::RETURN_STATEMENT: Chris@0: return $stmt; Chris@0: case Database::RETURN_AFFECTED: Chris@0: $stmt->allowRowCount = TRUE; Chris@0: return $stmt->rowCount(); Chris@0: case Database::RETURN_INSERT_ID: Chris@0: $sequence_name = isset($options['sequence_name']) ? $options['sequence_name'] : NULL; Chris@0: return $this->connection->lastInsertId($sequence_name); Chris@0: case Database::RETURN_NULL: Chris@0: return NULL; Chris@0: default: Chris@0: throw new \PDOException('Invalid return directive: ' . $options['return']); Chris@0: } Chris@0: } Chris@0: catch (\PDOException $e) { Chris@0: // Most database drivers will return NULL here, but some of them Chris@0: // (e.g. the SQLite driver) may need to re-run the query, so the return Chris@0: // value will be the same as for static::query(). Chris@0: return $this->handleQueryException($e, $query, $args, $options); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Wraps and re-throws any PDO exception thrown by static::query(). Chris@0: * Chris@0: * @param \PDOException $e Chris@0: * The exception thrown by static::query(). Chris@0: * @param $query Chris@0: * The query executed by static::query(). Chris@0: * @param array $args Chris@0: * An array of arguments for the prepared statement. Chris@0: * @param array $options Chris@0: * An associative array of options to control how the query is run. Chris@0: * Chris@0: * @return \Drupal\Core\Database\StatementInterface|int|null Chris@0: * Most database drivers will return NULL when a PDO exception is thrown for Chris@0: * a query, but some of them may need to re-run the query, so they can also Chris@0: * return a \Drupal\Core\Database\StatementInterface object or an integer. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\DatabaseExceptionWrapper Chris@0: * @throws \Drupal\Core\Database\IntegrityConstraintViolationException Chris@0: */ Chris@0: protected function handleQueryException(\PDOException $e, $query, array $args = [], $options = []) { Chris@0: if ($options['throw_exception']) { Chris@0: // Wrap the exception in another exception, because PHP does not allow Chris@0: // overriding Exception::getMessage(). Its message is the extra database Chris@0: // debug information. Chris@0: $query_string = ($query instanceof StatementInterface) ? $query->getQueryString() : $query; Chris@0: $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE); Chris@0: // Match all SQLSTATE 23xxx errors. Chris@0: if (substr($e->getCode(), -6, -3) == '23') { Chris@0: $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e); Chris@0: } Chris@0: else { Chris@0: $exception = new DatabaseExceptionWrapper($message, 0, $e); Chris@0: } Chris@0: Chris@0: throw $exception; Chris@0: } Chris@0: Chris@0: return NULL; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Expands out shorthand placeholders. Chris@0: * Chris@0: * Drupal supports an alternate syntax for doing arrays of values. We Chris@0: * therefore need to expand them out into a full, executable query string. Chris@0: * Chris@0: * @param string $query Chris@0: * The query string to modify. Chris@0: * @param array $args Chris@0: * The arguments for the query. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if the query was modified, FALSE otherwise. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * This exception is thrown when: Chris@0: * - A placeholder that ends in [] is supplied, and the supplied value is Chris@0: * not an array. Chris@0: * - A placeholder that does not end in [] is supplied, and the supplied Chris@0: * value is an array. Chris@0: */ Chris@0: protected function expandArguments(&$query, &$args) { Chris@0: $modified = FALSE; Chris@0: Chris@0: // If the placeholder indicated the value to use is an array, we need to Chris@0: // expand it out into a comma-delimited set of placeholders. Chris@0: foreach ($args as $key => $data) { Chris@0: $is_bracket_placeholder = substr($key, -2) === '[]'; Chris@0: $is_array_data = is_array($data); Chris@0: if ($is_bracket_placeholder && !$is_array_data) { Chris@0: throw new \InvalidArgumentException('Placeholders with a trailing [] can only be expanded with an array of values.'); Chris@0: } Chris@0: elseif (!$is_bracket_placeholder) { Chris@0: if ($is_array_data) { Chris@0: throw new \InvalidArgumentException('Placeholders must have a trailing [] if they are to be expanded with an array of values.'); Chris@0: } Chris@0: // Scalar placeholder - does not need to be expanded. Chris@0: continue; Chris@0: } Chris@0: // Handle expansion of arrays. Chris@0: $key_name = str_replace('[]', '__', $key); Chris@0: $new_keys = []; Chris@0: // We require placeholders to have trailing brackets if the developer Chris@0: // intends them to be expanded to an array to make the intent explicit. Chris@0: foreach (array_values($data) as $i => $value) { Chris@0: // This assumes that there are no other placeholders that use the same Chris@0: // name. For example, if the array placeholder is defined as :example[] Chris@0: // and there is already an :example_2 placeholder, this will generate Chris@0: // a duplicate key. We do not account for that as the calling code Chris@0: // is already broken if that happens. Chris@0: $new_keys[$key_name . $i] = $value; Chris@0: } Chris@0: Chris@0: // Update the query with the new placeholders. Chris@0: $query = str_replace($key, implode(', ', array_keys($new_keys)), $query); Chris@0: Chris@0: // Update the args array with the new placeholders. Chris@0: unset($args[$key]); Chris@0: $args += $new_keys; Chris@0: Chris@0: $modified = TRUE; Chris@0: } Chris@0: Chris@0: return $modified; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the driver-specific override class if any for the specified class. Chris@0: * Chris@0: * @param string $class Chris@0: * The class for which we want the potentially driver-specific class. Chris@0: * @return string Chris@0: * The name of the class that should be used for this driver. Chris@0: */ Chris@0: public function getDriverClass($class) { Chris@0: if (empty($this->driverClasses[$class])) { Chris@0: if (empty($this->connectionOptions['namespace'])) { Chris@0: // Fallback for Drupal 7 settings.php and the test runner script. Chris@0: $this->connectionOptions['namespace'] = (new \ReflectionObject($this))->getNamespaceName(); Chris@0: } Chris@0: $driver_class = $this->connectionOptions['namespace'] . '\\' . $class; Chris@0: $this->driverClasses[$class] = class_exists($driver_class) ? $driver_class : $class; Chris@0: } Chris@0: return $this->driverClasses[$class]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns a SELECT query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The base table for this query, that is, the first table in the FROM Chris@0: * clause. This table will also be used as the "base" table for query_alter Chris@0: * hook implementations. Chris@0: * @param string $alias Chris@0: * (optional) The alias of the base table of this query. Chris@0: * @param $options Chris@0: * An array of options on the query. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\SelectInterface Chris@0: * An appropriate SelectQuery object for this database connection. Note that Chris@0: * it may be a driver-specific subclass of SelectQuery, depending on the Chris@0: * driver. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Select Chris@0: */ Chris@0: public function select($table, $alias = NULL, array $options = []) { Chris@0: $class = $this->getDriverClass('Select'); Chris@0: return new $class($table, $alias, $this, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns an INSERT query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the insert statement. Chris@0: * @param array $options Chris@17: * (optional) An associative array of options to control how the query is Chris@17: * run. The given options will be merged with Chris@17: * \Drupal\Core\Database\Connection::defaultOptions(). Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Insert Chris@0: * A new Insert query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Insert Chris@17: * @see \Drupal\Core\Database\Connection::defaultOptions() Chris@0: */ Chris@0: public function insert($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Insert'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns a MERGE query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the merge statement. Chris@0: * @param array $options Chris@0: * (optional) An array of options on the query. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Merge Chris@0: * A new Merge query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Merge Chris@0: */ Chris@0: public function merge($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Merge'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns an UPSERT query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the upsert query. Chris@0: * @param array $options Chris@0: * (optional) An array of options on the query. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Upsert Chris@0: * A new Upsert query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Upsert Chris@0: */ Chris@0: public function upsert($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Upsert'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns an UPDATE query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the update statement. Chris@0: * @param array $options Chris@17: * (optional) An associative array of options to control how the query is Chris@17: * run. The given options will be merged with Chris@17: * \Drupal\Core\Database\Connection::defaultOptions(). Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Update Chris@0: * A new Update query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Update Chris@17: * @see \Drupal\Core\Database\Connection::defaultOptions() Chris@0: */ Chris@0: public function update($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Update'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns a DELETE query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the delete statement. Chris@0: * @param array $options Chris@17: * (optional) An associative array of options to control how the query is Chris@17: * run. The given options will be merged with Chris@17: * \Drupal\Core\Database\Connection::defaultOptions(). Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Delete Chris@0: * A new Delete query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Delete Chris@17: * @see \Drupal\Core\Database\Connection::defaultOptions() Chris@0: */ Chris@0: public function delete($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Delete'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares and returns a TRUNCATE query object. Chris@0: * Chris@0: * @param string $table Chris@0: * The table to use for the truncate statement. Chris@0: * @param array $options Chris@0: * (optional) An array of options on the query. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Query\Truncate Chris@0: * A new Truncate query object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Truncate Chris@0: */ Chris@0: public function truncate($table, array $options = []) { Chris@0: $class = $this->getDriverClass('Truncate'); Chris@0: return new $class($this, $table, $options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a DatabaseSchema object for manipulating the schema. Chris@0: * Chris@0: * This method will lazy-load the appropriate schema library file. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Schema Chris@0: * The database Schema object for this connection. Chris@0: */ Chris@0: public function schema() { Chris@0: if (empty($this->schema)) { Chris@0: $class = $this->getDriverClass('Schema'); Chris@0: $this->schema = new $class($this); Chris@0: } Chris@0: return $this->schema; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Escapes a database name string. Chris@0: * Chris@0: * Force all database names to be strictly alphanumeric-plus-underscore. Chris@0: * For some database drivers, it may also wrap the database name in Chris@0: * database-specific escape characters. Chris@0: * Chris@0: * @param string $database Chris@0: * An unsanitized database name. Chris@0: * Chris@0: * @return string Chris@0: * The sanitized database name. Chris@0: */ Chris@0: public function escapeDatabase($database) { Chris@0: if (!isset($this->escapedNames[$database])) { Chris@0: $this->escapedNames[$database] = preg_replace('/[^A-Za-z0-9_.]+/', '', $database); Chris@0: } Chris@0: return $this->escapedNames[$database]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Escapes a table name string. Chris@0: * Chris@0: * Force all table names to be strictly alphanumeric-plus-underscore. Chris@0: * For some database drivers, it may also wrap the table name in Chris@0: * database-specific escape characters. Chris@0: * Chris@0: * @param string $table Chris@0: * An unsanitized table name. Chris@0: * Chris@0: * @return string Chris@0: * The sanitized table name. Chris@0: */ Chris@0: public function escapeTable($table) { Chris@0: if (!isset($this->escapedNames[$table])) { Chris@0: $this->escapedNames[$table] = preg_replace('/[^A-Za-z0-9_.]+/', '', $table); Chris@0: } Chris@0: return $this->escapedNames[$table]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Escapes a field name string. Chris@0: * Chris@0: * Force all field names to be strictly alphanumeric-plus-underscore. Chris@0: * For some database drivers, it may also wrap the field name in Chris@0: * database-specific escape characters. Chris@0: * Chris@0: * @param string $field Chris@0: * An unsanitized field name. Chris@0: * Chris@0: * @return string Chris@0: * The sanitized field name. Chris@0: */ Chris@0: public function escapeField($field) { Chris@0: if (!isset($this->escapedNames[$field])) { Chris@0: $this->escapedNames[$field] = preg_replace('/[^A-Za-z0-9_.]+/', '', $field); Chris@0: } Chris@0: return $this->escapedNames[$field]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Escapes an alias name string. Chris@0: * Chris@0: * Force all alias names to be strictly alphanumeric-plus-underscore. In Chris@0: * contrast to DatabaseConnection::escapeField() / Chris@0: * DatabaseConnection::escapeTable(), this doesn't allow the period (".") Chris@0: * because that is not allowed in aliases. Chris@0: * Chris@0: * @param string $field Chris@0: * An unsanitized alias name. Chris@0: * Chris@0: * @return string Chris@0: * The sanitized alias name. Chris@0: */ Chris@0: public function escapeAlias($field) { Chris@0: if (!isset($this->escapedAliases[$field])) { Chris@0: $this->escapedAliases[$field] = preg_replace('/[^A-Za-z0-9_]+/', '', $field); Chris@0: } Chris@0: return $this->escapedAliases[$field]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Escapes characters that work as wildcard characters in a LIKE pattern. Chris@0: * Chris@0: * The wildcard characters "%" and "_" as well as backslash are prefixed with Chris@0: * a backslash. Use this to do a search for a verbatim string without any Chris@0: * wildcard behavior. Chris@0: * Chris@0: * For example, the following does a case-insensitive query for all rows whose Chris@0: * name starts with $prefix: Chris@0: * @code Chris@0: * $result = db_query( Chris@0: * 'SELECT * FROM person WHERE name LIKE :pattern', Chris@18: * array(':pattern' => $injected_connection->escapeLike($prefix) . '%') Chris@0: * ); Chris@0: * @endcode Chris@0: * Chris@0: * Backslash is defined as escape character for LIKE patterns in Chris@0: * Drupal\Core\Database\Query\Condition::mapConditionOperator(). Chris@0: * Chris@0: * @param string $string Chris@0: * The string to escape. Chris@0: * Chris@0: * @return string Chris@0: * The escaped string. Chris@0: */ Chris@0: public function escapeLike($string) { Chris@0: return addcslashes($string, '\%_'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines if there is an active transaction open. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if we're currently in a transaction, FALSE otherwise. Chris@0: */ Chris@0: public function inTransaction() { Chris@0: return ($this->transactionDepth() > 0); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines the current transaction depth. Chris@0: * Chris@0: * @return int Chris@0: * The current transaction depth. Chris@0: */ Chris@0: public function transactionDepth() { Chris@0: return count($this->transactionLayers); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a new DatabaseTransaction object on this connection. Chris@0: * Chris@0: * @param string $name Chris@0: * (optional) The name of the savepoint. Chris@0: * Chris@0: * @return \Drupal\Core\Database\Transaction Chris@0: * A Transaction object. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Transaction Chris@0: */ Chris@0: public function startTransaction($name = '') { Chris@0: $class = $this->getDriverClass('Transaction'); Chris@0: return new $class($this, $name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Rolls back the transaction entirely or to a named savepoint. Chris@0: * Chris@0: * This method throws an exception if no transaction is active. Chris@0: * Chris@0: * @param string $savepoint_name Chris@0: * (optional) The name of the savepoint. The default, 'drupal_transaction', Chris@0: * will roll the entire transaction back. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\TransactionOutOfOrderException Chris@0: * @throws \Drupal\Core\Database\TransactionNoActiveException Chris@0: * Chris@0: * @see \Drupal\Core\Database\Transaction::rollBack() Chris@0: */ Chris@0: public function rollBack($savepoint_name = 'drupal_transaction') { Chris@0: if (!$this->supportsTransactions()) { Chris@0: return; Chris@0: } Chris@0: if (!$this->inTransaction()) { Chris@0: throw new TransactionNoActiveException(); Chris@0: } Chris@0: // A previous rollback to an earlier savepoint may mean that the savepoint Chris@0: // in question has already been accidentally committed. Chris@0: if (!isset($this->transactionLayers[$savepoint_name])) { Chris@0: throw new TransactionNoActiveException(); Chris@0: } Chris@0: Chris@0: // We need to find the point we're rolling back to, all other savepoints Chris@0: // before are no longer needed. If we rolled back other active savepoints, Chris@0: // we need to throw an exception. Chris@0: $rolled_back_other_active_savepoints = FALSE; Chris@0: while ($savepoint = array_pop($this->transactionLayers)) { Chris@0: if ($savepoint == $savepoint_name) { Chris@0: // If it is the last the transaction in the stack, then it is not a Chris@0: // savepoint, it is the transaction itself so we will need to roll back Chris@0: // the transaction rather than a savepoint. Chris@0: if (empty($this->transactionLayers)) { Chris@0: break; Chris@0: } Chris@0: $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint); Chris@0: $this->popCommittableTransactions(); Chris@0: if ($rolled_back_other_active_savepoints) { Chris@0: throw new TransactionOutOfOrderException(); Chris@0: } Chris@0: return; Chris@0: } Chris@0: else { Chris@0: $rolled_back_other_active_savepoints = TRUE; Chris@0: } Chris@0: } Chris@0: $this->connection->rollBack(); Chris@0: if ($rolled_back_other_active_savepoints) { Chris@0: throw new TransactionOutOfOrderException(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Increases the depth of transaction nesting. Chris@0: * Chris@0: * If no transaction is already active, we begin a new transaction. Chris@0: * Chris@0: * @param string $name Chris@0: * The name of the transaction. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\TransactionNameNonUniqueException Chris@0: * Chris@0: * @see \Drupal\Core\Database\Transaction Chris@0: */ Chris@0: public function pushTransaction($name) { Chris@0: if (!$this->supportsTransactions()) { Chris@0: return; Chris@0: } Chris@0: if (isset($this->transactionLayers[$name])) { Chris@0: throw new TransactionNameNonUniqueException($name . " is already in use."); Chris@0: } Chris@0: // If we're already in a transaction then we want to create a savepoint Chris@0: // rather than try to create another transaction. Chris@0: if ($this->inTransaction()) { Chris@0: $this->query('SAVEPOINT ' . $name); Chris@0: } Chris@0: else { Chris@0: $this->connection->beginTransaction(); Chris@0: } Chris@0: $this->transactionLayers[$name] = $name; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Decreases the depth of transaction nesting. Chris@0: * Chris@0: * If we pop off the last transaction layer, then we either commit or roll Chris@0: * back the transaction as necessary. If no transaction is active, we return Chris@0: * because the transaction may have manually been rolled back. Chris@0: * Chris@0: * @param string $name Chris@0: * The name of the savepoint. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\TransactionNoActiveException Chris@0: * @throws \Drupal\Core\Database\TransactionCommitFailedException Chris@0: * Chris@0: * @see \Drupal\Core\Database\Transaction Chris@0: */ Chris@0: public function popTransaction($name) { Chris@0: if (!$this->supportsTransactions()) { Chris@0: return; Chris@0: } Chris@0: // The transaction has already been committed earlier. There is nothing we Chris@0: // need to do. If this transaction was part of an earlier out-of-order Chris@0: // rollback, an exception would already have been thrown by Chris@0: // Database::rollBack(). Chris@0: if (!isset($this->transactionLayers[$name])) { Chris@0: return; Chris@0: } Chris@0: Chris@0: // Mark this layer as committable. Chris@0: $this->transactionLayers[$name] = FALSE; Chris@0: $this->popCommittableTransactions(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Internal function: commit all the transaction layers that can commit. Chris@0: */ Chris@0: protected function popCommittableTransactions() { Chris@0: // Commit all the committable layers. Chris@0: foreach (array_reverse($this->transactionLayers) as $name => $active) { Chris@0: // Stop once we found an active transaction. Chris@0: if ($active) { Chris@0: break; Chris@0: } Chris@0: Chris@0: // If there are no more layers left then we should commit. Chris@0: unset($this->transactionLayers[$name]); Chris@0: if (empty($this->transactionLayers)) { Chris@0: if (!$this->connection->commit()) { Chris@0: throw new TransactionCommitFailedException(); Chris@0: } Chris@0: } Chris@0: else { Chris@0: $this->query('RELEASE SAVEPOINT ' . $name); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs a limited-range query on this database object. Chris@0: * Chris@0: * Use this as a substitute for ->query() when a subset of the query is to be Chris@0: * returned. User-supplied arguments to the query should be passed in as Chris@0: * separate parameters so that they can be properly escaped to avoid SQL Chris@0: * injection attacks. Chris@0: * Chris@0: * @param string $query Chris@0: * A string containing an SQL query. Chris@0: * @param int $from Chris@0: * The first result row to return. Chris@0: * @param int $count Chris@0: * The maximum number of result rows to return. Chris@0: * @param array $args Chris@0: * (optional) An array of values to substitute into the query at placeholder Chris@0: * markers. Chris@0: * @param array $options Chris@0: * (optional) An array of options on the query. Chris@0: * Chris@0: * @return \Drupal\Core\Database\StatementInterface Chris@0: * A database query result resource, or NULL if the query was not executed Chris@0: * correctly. Chris@0: */ Chris@0: abstract public function queryRange($query, $from, $count, array $args = [], array $options = []); Chris@0: Chris@0: /** Chris@0: * Generates a temporary table name. Chris@0: * Chris@0: * @return string Chris@0: * A table name. Chris@0: */ Chris@0: protected function generateTemporaryTableName() { Chris@0: return "db_temporary_" . $this->temporaryNameIndex++; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs a SELECT query and stores its results in a temporary table. Chris@0: * Chris@0: * Use this as a substitute for ->query() when the results need to stored Chris@0: * in a temporary table. Temporary tables exist for the duration of the page Chris@0: * request. User-supplied arguments to the query should be passed in as Chris@0: * separate parameters so that they can be properly escaped to avoid SQL Chris@0: * injection attacks. Chris@0: * Chris@0: * Note that if you need to know how many results were returned, you should do Chris@0: * a SELECT COUNT(*) on the temporary table afterwards. Chris@0: * Chris@0: * @param string $query Chris@0: * A string containing a normal SELECT SQL query. Chris@0: * @param array $args Chris@0: * (optional) An array of values to substitute into the query at placeholder Chris@0: * markers. Chris@0: * @param array $options Chris@0: * (optional) An associative array of options to control how the query is Chris@0: * run. See the documentation for DatabaseConnection::defaultOptions() for Chris@0: * details. Chris@0: * Chris@0: * @return string Chris@0: * The name of the temporary table. Chris@0: */ Chris@0: abstract public function queryTemporary($query, array $args = [], array $options = []); Chris@0: Chris@0: /** Chris@0: * Returns the type of database driver. Chris@0: * Chris@0: * This is not necessarily the same as the type of the database itself. For Chris@0: * instance, there could be two MySQL drivers, mysql and mysql_mock. This Chris@0: * function would return different values for each, but both would return Chris@0: * "mysql" for databaseType(). Chris@0: * Chris@0: * @return string Chris@0: * The type of database driver. Chris@0: */ Chris@0: abstract public function driver(); Chris@0: Chris@0: /** Chris@0: * Returns the version of the database server. Chris@0: */ Chris@0: public function version() { Chris@0: return $this->connection->getAttribute(\PDO::ATTR_SERVER_VERSION); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the version of the database client. Chris@0: */ Chris@0: public function clientVersion() { Chris@0: return $this->connection->getAttribute(\PDO::ATTR_CLIENT_VERSION); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines if this driver supports transactions. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if this connection supports transactions, FALSE otherwise. Chris@0: */ Chris@0: public function supportsTransactions() { Chris@0: return $this->transactionSupport; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Determines if this driver supports transactional DDL. Chris@0: * Chris@0: * DDL queries are those that change the schema, such as ALTER queries. Chris@0: * Chris@0: * @return bool Chris@0: * TRUE if this connection supports transactions for DDL queries, FALSE Chris@0: * otherwise. Chris@0: */ Chris@0: public function supportsTransactionalDDL() { Chris@0: return $this->transactionalDDLSupport; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the name of the PDO driver for this connection. Chris@0: */ Chris@0: abstract public function databaseType(); Chris@0: Chris@0: /** Chris@0: * Creates a database. Chris@0: * Chris@0: * In order to use this method, you must be connected without a database Chris@0: * specified. Chris@0: * Chris@0: * @param string $database Chris@0: * The name of the database to create. Chris@0: */ Chris@0: abstract public function createDatabase($database); Chris@0: Chris@0: /** Chris@0: * Gets any special processing requirements for the condition operator. Chris@0: * Chris@0: * Some condition types require special processing, such as IN, because Chris@0: * the value data they pass in is not a simple value. This is a simple Chris@0: * overridable lookup function. Database connections should define only Chris@0: * those operators they wish to be handled differently than the default. Chris@0: * Chris@0: * @param string $operator Chris@0: * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive. Chris@0: * Chris@0: * @return Chris@0: * The extra handling directives for the specified operator, or NULL. Chris@0: * Chris@0: * @see \Drupal\Core\Database\Query\Condition::compile() Chris@0: */ Chris@0: abstract public function mapConditionOperator($operator); Chris@0: Chris@0: /** Chris@0: * Throws an exception to deny direct access to transaction commits. Chris@0: * Chris@0: * We do not want to allow users to commit transactions at any time, only Chris@0: * by destroying the transaction object or allowing it to go out of scope. Chris@0: * A direct commit bypasses all of the safety checks we've built on top of Chris@0: * PDO's transaction routines. Chris@0: * Chris@0: * @throws \Drupal\Core\Database\TransactionExplicitCommitNotAllowedException Chris@0: * Chris@0: * @see \Drupal\Core\Database\Transaction Chris@0: */ Chris@0: public function commit() { Chris@0: throw new TransactionExplicitCommitNotAllowedException(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves an unique ID from a given sequence. Chris@0: * Chris@0: * Use this function if for some reason you can't use a serial field. For Chris@0: * example, MySQL has no ways of reading of the current value of a sequence Chris@0: * and PostgreSQL can not advance the sequence to be larger than a given Chris@0: * value. Or sometimes you just need a unique integer. Chris@0: * Chris@0: * @param $existing_id Chris@0: * (optional) After a database import, it might be that the sequences table Chris@0: * is behind, so by passing in the maximum existing ID, it can be assured Chris@0: * that we never issue the same ID. Chris@0: * Chris@0: * @return Chris@0: * An integer number larger than any number returned by earlier calls and Chris@0: * also larger than the $existing_id if one was passed in. Chris@0: */ Chris@0: abstract public function nextId($existing_id = 0); Chris@0: Chris@0: /** Chris@0: * Prepares a statement for execution and returns a statement object Chris@0: * Chris@0: * Emulated prepared statements does not communicate with the database server Chris@0: * so this method does not check the statement. Chris@0: * Chris@0: * @param string $statement Chris@0: * This must be a valid SQL statement for the target database server. Chris@0: * @param array $driver_options Chris@0: * (optional) This array holds one or more key=>value pairs to set Chris@0: * attribute values for the PDOStatement object that this method returns. Chris@0: * You would most commonly use this to set the \PDO::ATTR_CURSOR value to Chris@0: * \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have Chris@0: * driver specific options that may be set at prepare-time. Defaults to an Chris@0: * empty array. Chris@0: * Chris@0: * @return \PDOStatement|false Chris@0: * If the database server successfully prepares the statement, returns a Chris@0: * \PDOStatement object. Chris@0: * If the database server cannot successfully prepare the statement returns Chris@0: * FALSE or emits \PDOException (depending on error handling). Chris@0: * Chris@0: * @throws \PDOException Chris@0: * Chris@0: * @see \PDO::prepare() Chris@0: */ Chris@0: public function prepare($statement, array $driver_options = []) { Chris@0: return $this->connection->prepare($statement, $driver_options); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Quotes a string for use in a query. Chris@0: * Chris@0: * @param string $string Chris@0: * The string to be quoted. Chris@0: * @param int $parameter_type Chris@0: * (optional) Provides a data type hint for drivers that have alternate Chris@0: * quoting styles. Defaults to \PDO::PARAM_STR. Chris@0: * Chris@0: * @return string|bool Chris@0: * A quoted string that is theoretically safe to pass into an SQL statement. Chris@0: * Returns FALSE if the driver does not support quoting in this way. Chris@0: * Chris@0: * @see \PDO::quote() Chris@0: */ Chris@0: public function quote($string, $parameter_type = \PDO::PARAM_STR) { Chris@0: return $this->connection->quote($string, $parameter_type); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Extracts the SQLSTATE error from the PDOException. Chris@0: * Chris@0: * @param \Exception $e Chris@0: * The exception Chris@0: * Chris@0: * @return string Chris@0: * The five character error code. Chris@0: */ Chris@0: protected static function getSQLState(\Exception $e) { Chris@0: // The PDOException code is not always reliable, try to see whether the Chris@0: // message has something usable. Chris@0: if (preg_match('/^SQLSTATE\[(\w{5})\]/', $e->getMessage(), $matches)) { Chris@0: return $matches[1]; Chris@0: } Chris@0: else { Chris@0: return $e->getCode(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prevents the database connection from being serialized. Chris@0: */ Chris@0: public function __sleep() { Chris@0: throw new \LogicException('The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution.'); Chris@0: } Chris@0: Chris@17: /** Chris@17: * Creates an array of database connection options from a URL. Chris@17: * Chris@17: * @internal Chris@17: * This method should not be called. Use Chris@17: * \Drupal\Core\Database\Database::convertDbUrlToConnectionInfo() instead. Chris@17: * Chris@17: * @param string $url Chris@17: * The URL. Chris@17: * @param string $root Chris@17: * The root directory of the Drupal installation. Some database drivers, Chris@17: * like for example SQLite, need this information. Chris@17: * Chris@17: * @return array Chris@17: * The connection options. Chris@17: * Chris@17: * @throws \InvalidArgumentException Chris@17: * Exception thrown when the provided URL does not meet the minimum Chris@17: * requirements. Chris@17: * Chris@17: * @see \Drupal\Core\Database\Database::convertDbUrlToConnectionInfo() Chris@17: */ Chris@17: public static function createConnectionOptionsFromUrl($url, $root) { Chris@17: $url_components = parse_url($url); Chris@17: if (!isset($url_components['scheme'], $url_components['host'], $url_components['path'])) { Chris@17: throw new \InvalidArgumentException('Minimum requirement: driver://host/database'); Chris@17: } Chris@17: Chris@17: $url_components += [ Chris@17: 'user' => '', Chris@17: 'pass' => '', Chris@17: 'fragment' => '', Chris@17: ]; Chris@17: Chris@17: // Remove leading slash from the URL path. Chris@17: if ($url_components['path'][0] === '/') { Chris@17: $url_components['path'] = substr($url_components['path'], 1); Chris@17: } Chris@17: Chris@17: // Use reflection to get the namespace of the class being called. Chris@17: $reflector = new \ReflectionClass(get_called_class()); Chris@17: Chris@17: $database = [ Chris@17: 'driver' => $url_components['scheme'], Chris@17: 'username' => $url_components['user'], Chris@17: 'password' => $url_components['pass'], Chris@17: 'host' => $url_components['host'], Chris@17: 'database' => $url_components['path'], Chris@17: 'namespace' => $reflector->getNamespaceName(), Chris@17: ]; Chris@17: Chris@17: if (isset($url_components['port'])) { Chris@17: $database['port'] = $url_components['port']; Chris@17: } Chris@17: Chris@17: if (!empty($url_components['fragment'])) { Chris@17: $database['prefix']['default'] = $url_components['fragment']; Chris@17: } Chris@17: Chris@17: return $database; Chris@17: } Chris@17: Chris@17: /** Chris@17: * Creates a URL from an array of database connection options. Chris@17: * Chris@17: * @internal Chris@17: * This method should not be called. Use Chris@17: * \Drupal\Core\Database\Database::getConnectionInfoAsUrl() instead. Chris@17: * Chris@17: * @param array $connection_options Chris@17: * The array of connection options for a database connection. Chris@17: * Chris@17: * @return string Chris@17: * The connection info as a URL. Chris@17: * Chris@17: * @throws \InvalidArgumentException Chris@17: * Exception thrown when the provided array of connection options does not Chris@17: * meet the minimum requirements. Chris@17: * Chris@17: * @see \Drupal\Core\Database\Database::getConnectionInfoAsUrl() Chris@17: */ Chris@17: public static function createUrlFromConnectionOptions(array $connection_options) { Chris@17: if (!isset($connection_options['driver'], $connection_options['database'])) { Chris@17: throw new \InvalidArgumentException("As a minimum, the connection options array must contain at least the 'driver' and 'database' keys"); Chris@17: } Chris@17: Chris@17: $user = ''; Chris@17: if (isset($connection_options['username'])) { Chris@17: $user = $connection_options['username']; Chris@17: if (isset($connection_options['password'])) { Chris@17: $user .= ':' . $connection_options['password']; Chris@17: } Chris@17: $user .= '@'; Chris@17: } Chris@17: Chris@17: $host = empty($connection_options['host']) ? 'localhost' : $connection_options['host']; Chris@17: Chris@17: $db_url = $connection_options['driver'] . '://' . $user . $host; Chris@17: Chris@17: if (isset($connection_options['port'])) { Chris@17: $db_url .= ':' . $connection_options['port']; Chris@17: } Chris@17: Chris@17: $db_url .= '/' . $connection_options['database']; Chris@17: Chris@17: if (isset($connection_options['prefix']['default']) && $connection_options['prefix']['default'] !== '') { Chris@17: $db_url .= '#' . $connection_options['prefix']['default']; Chris@17: } Chris@17: Chris@17: return $db_url; Chris@17: } Chris@17: Chris@0: }