class Connection extends Connection (View source)

MySQL implementation of \Drupal\Core\Database\Connection.

Constants

DATABASE_NOT_FOUND

Error code for "Unknown database" error.

ACCESS_DENIED

Error code for "Access denied" error.

UNSUPPORTED_CHARSET

Error code for "Can't initialize character set" error.

UNKNOWN_CHARSET

Driver-specific error code for "Unknown character set" error.

SQLSTATE_SYNTAX_ERROR

SQLSTATE error code for "Syntax error or access rule violation".

MIN_MAX_ALLOWED_PACKET

The minimal possible value for the max_allowed_packet setting of MySQL.

Properties

protected string|null $target

The database target this connection is for.

from  Connection
protected string|null $key

The key representing this connection.

from  Connection
protected Log|null $logger

The current database logging object for this connection.

from  Connection
protected array $transactionLayers

Tracks the number of "layers" of transactions currently active.

from  Connection
protected array $driverClasses

Index of what driver-specific class to use for various operations.

from  Connection
protected $statementClass {@inheritdoc}
protected $statementWrapperClass {@inheritdoc}
protected bool $transactionalDDLSupport

Whether this database connection supports transactional DDL.

from  Connection
protected int deprecated $temporaryNameIndex

An index used to generate unique temporary table names.

from  Connection
protected PDO $connection

The actual PDO connection.

from  Connection
protected array $connectionOptions

The connection information for this connection object.

from  Connection
protected Schema|null $schema

The schema object for this connection.

from  Connection
protected array $prefixes

The prefixes used by this database connection.

from  Connection
protected array $prefixSearch

List of search values for use in prefixTables().

from  Connection
protected array $prefixReplace

List of replacement values for use in prefixTables().

from  Connection
protected array $unprefixedTablesMap

List of un-prefixed table names, keyed by prefixed table names.

from  Connection
protected array deprecated $escapedNames

List of escaped database, table, and field names, keyed by unescaped names.

from  Connection
protected array $escapedTables

List of escaped table names, keyed by unescaped names.

from  Connection
protected array $escapedFields

List of escaped field names, keyed by unescaped names.

from  Connection
protected array $escapedAliases

List of escaped aliases names, keyed by unescaped aliases.

from  Connection
protected callable[] $rootTransactionEndCallbacks

Post-root (non-nested) transaction commit callbacks.

from  Connection
protected $identifierQuotes {@inheritdoc}
protected bool $needsCleanup

Flag to indicate if the cleanup function in __destruct() should run.

Methods

__construct(PDO $connection, array $connection_options)

Constructs a Connection object.

static PDO
open(array $connection_options = [])

Opens a PDO connection.

destroy() deprecated

Destroys this Connection object.

__destruct()

Ensures that the PDO connection can be garbage collected.

array
defaultOptions()

Returns the default query options for any given query.

array
getConnectionOptions()

Returns the connection information for this connection object.

void
attachDatabase(string $database)

Allows the connection to access additional databases.

setPrefix(array|string $prefix)

Set the list of prefixes used by this database connection.

string
prefixTables(string $sql)

Appends a database prefix to all tables in a query.

string
quoteIdentifiers(string $sql)

Quotes all identifiers in a query.

tablePrefix(string $table = 'default')

Find the prefix for a table.

array
getUnprefixedTablesMap()

Gets a list of individually prefixed table names.

string
getFullQualifiedTableName(string $table)

Get a fully qualified table name.

prepareStatement(string $query, array $options, bool $allow_row_count = FALSE)

Returns a prepared statement given a SQL string.

string
preprocessStatement(string $query, array $options)

Returns a string SQL statement ready for preparation.

prepareQuery($query, bool $quote_identifiers = TRUE) deprecated

Prepares a query string and returns the prepared statement.

setTarget(string $target = NULL)

Tells this connection object what its target value is.

string|null
getTarget()

Returns the target this connection is associated with.

setKey(string $key)

Tells this connection object what its key is.

string|null
getKey()

Returns the key this connection is associated with.

setLogger(Log $logger)

Associates a logging object with this connection.

Log|null
getLogger()

Gets the current logging object for this connection.

string
makeSequenceName(string $table, string $field)

Creates the appropriate sequence name for a given table and serial field.

string
makeComment(string[] $comments)

Flatten an array of query comments into a single comment string.

string
filterComment(string $comment = '')

Sanitize a query comment string.

StatementInterface|int|string|null
query(string|StatementInterface|PDOStatement $query, array $args = [], array $options = [])

Executes a query string against the database.

handleQueryException(PDOException $e, $query, array $args = [], array $options = [])

Wraps and re-throws any PDO exception thrown by static::query().

bool
expandArguments(string $query, array $args)

Expands out shorthand placeholders.

string
getDriverClass(string $class)

Gets the driver-specific override class if any for the specified class.

exceptionHandler()

Returns the database exceptions handler.

select(string|SelectInterface $table, string $alias = NULL, array $options = [])

Prepares and returns a SELECT query object.

insert(string $table, array $options = [])

Prepares and returns an INSERT query object.

merge(string $table, array $options = [])

Prepares and returns a MERGE query object.

upsert(string $table, array $options = [])

Prepares and returns an UPSERT query object.

update(string $table, array $options = [])

Prepares and returns an UPDATE query object.

delete(string $table, array $options = [])

Prepares and returns a DELETE query object.

truncate(string $table, array $options = [])

Prepares and returns a TRUNCATE query object.

schema()

Returns a DatabaseSchema object for manipulating the schema.

condition(string $conjunction)

Prepares and returns a CONDITION query object.

string
escapeDatabase(string $database)

Escapes a database name string.

string
escapeTable(string $table)

Escapes a table name string.

string
escapeField(string $field)

Escapes a field name string.

string
escapeAlias(string $field)

Escapes an alias name string.

string
escapeLike(string $string)

Escapes characters that work as wildcard characters in a LIKE pattern.

bool
inTransaction()

Determines if there is an active transaction open.

int
transactionDepth()

Determines the current transaction depth.

startTransaction(string $name = '')

Returns a new DatabaseTransaction object on this connection.

rollBack(string $savepoint_name = 'drupal_transaction')

Rolls back the transaction entirely or to a named savepoint.

pushTransaction(string $name)

Increases the depth of transaction nesting.

popTransaction(string $name)

Decreases the depth of transaction nesting.

addRootTransactionEndCallback(callable $callback)

Adds a root transaction end callback.

popCommittableTransactions()

Overridden to work around issues to MySQL not supporting transactional DDL.

doCommit()

Do the actual commit, invoke post-commit callbacks.

queryRange(string $query, int $from, int $count, array $args = [], array $options = [])

Runs a limited-range query on this database object.

string
generateTemporaryTableName() deprecated

Generates a temporary table name.

string
queryTemporary(string $query, array $args = [], array $options = [])

Runs a SELECT query and stores its results in a temporary table.

string
driver()

Returns the type of database driver.

version()

Returns the version of the database server.

clientVersion()

Returns the version of the database client.

bool
supportsTransactions() deprecated

Determines if this driver supports transactions.

bool
supportsTransactionalDDL()

Determines if this driver supports transactional DDL.

databaseType()

Returns the name of the PDO driver for this connection.

createDatabase(string $database)

Overrides \Drupal\Core\Database\Connection::createDatabase().

The
mapConditionOperator(string $operator)

Gets any special processing requirements for the condition operator.

commit()

Throws an exception to deny direct access to transaction commits.

An
nextId($existing_id = 0)

Retrieves a unique ID from a given sequence.

PDOStatement|false
prepare(string $statement, array $driver_options = []) deprecated

Prepares a statement for execution and returns a statement object.

string|bool
quote(string $string, int $parameter_type = \PDO::PARAM_STR)

Quotes a string for use in a query.

static string
getSQLState(Exception $e)

Extracts the SQLSTATE error from the PDOException.

__sleep()

Prevents the database connection from being serialized.

static array
createConnectionOptionsFromUrl(string $url, string $root)

Creates an array of database connection options from a URL.

static string
createUrlFromConnectionOptions(array $connection_options)

Creates a URL from an array of database connection options.

string
getProvider()

Get the module name of the module that is providing the database driver.

getPagerManager()

Get the pager manager service, if available.

bool
isMariaDb()

Determines whether the MySQL distribution is MariaDB or not.

string|null
getMariaDbVersionMatch()

Gets the MariaDB portion of the server version.

string
getServerVersion()

Gets the server version.

nextIdDelete()

No description

Details

__construct(PDO $connection, array $connection_options)

Constructs a Connection object.

Parameters

PDO $connection

An object of the PDO class representing a database connection.

array $connection_options

An array of options for the connection. May include the following:

  • prefix
  • namespace
  • Other driver-specific options. An 'extra_prefix' option may be present to allow BC for attaching per-table prefixes, but it is meant for internal use only.

static PDO open(array $connection_options = [])

Opens a PDO connection.

Parameters

array $connection_options

The database connection settings array.

Return Value

PDO

A \PDO object.

destroy() deprecated

deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Move custom database destruction logic to __destruct().

Destroys this Connection object.

PHP does not destruct an object if it is still referenced in other variables. In case of PDO database connection objects, PHP only closes the connection when the PDO object is destructed, so any references to this object may cause the number of maximum allowed connections to be exceeded.

__destruct()

Ensures that the PDO connection can be garbage collected.

protected array defaultOptions()

Returns the default query options for any given query.

A given query can be customized with a number of option flags in an associative array:

  • fetch: This element controls how rows from a result set will be returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH, PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a class. If a string is specified, each record will be fetched into a new object of that class. The behavior of all other values is defined by PDO. See http://php.net/manual/pdostatement.fetch.php
  • return: Depending on the type of query, different return values may be meaningful. This directive instructs the system which type of return value is desired. The system will generally set the correct value automatically, so it is extremely rare that a module developer will ever need to specify this value. Setting it incorrectly will likely lead to unpredictable results or fatal errors. Legal values include:
    • Database::RETURN_STATEMENT: Return the prepared statement object for the query. This is usually only meaningful for SELECT queries, where the statement object is how one accesses the result set returned by the query.
    • Database::RETURN_AFFECTED: Return the number of rows affected by an UPDATE or DELETE query. Be aware that means the number of rows actually changed, not the number of rows matched by the WHERE clause.
    • Database::RETURN_INSERT_ID: Return the sequence ID (primary key) created by an INSERT statement on a table that contains a serial column.
    • Database::RETURN_NULL: Do not return anything, as there is no meaningful value to return. That is the case for INSERT queries on tables that do not contain a serial column.
  • throw_exception: (deprecated) By default, the database system will catch any errors on a query as an Exception, log it, and then rethrow it so that code further up the call chain can take an appropriate action. To suppress that behavior and simply return NULL on failure, set this option to FALSE.
  • allow_delimiter_in_query: By default, queries which have the ; delimiter any place in them will cause an exception. This reduces the chance of SQL injection attacks that terminate the original query and add one or more additional queries (such as inserting new user accounts). In rare cases, such as creating an SQL function, a ; is needed and can be allowed by changing this option to TRUE.
  • allow_square_brackets: By default, queries which contain square brackets will have them replaced with the identifier quote character for the database type. In rare cases, such as creating an SQL function, [] characters might be needed and can be allowed by changing this option to TRUE.
  • pdo: By default, queries will execute with the PDO options set on the connection. In particular cases, it could be necessary to override the PDO driver options on the statement level. In such case, pass the required setting as an array here, and they will be passed to the prepared statement. See https://www.php.net/manual/en/pdo.prepare.php.

Return Value

array

An array of default query options.

array getConnectionOptions()

Returns the connection information for this connection object.

Note that Database::getConnectionInfo() is for requesting information about an arbitrary database connection that is defined. This method is for requesting the connection information of this specific open connection object.

Return Value

array

An array of the connection information. The exact list of properties is driver-dependent.

void attachDatabase(string $database)

internal  
 

Allows the connection to access additional databases.

Database systems usually group tables in 'databases' or 'schemas', that can be accessed with syntax like 'SELECT * FROM database.table'. Normally Drupal accesses tables in a single database/schema, but in some cases it may be necessary to access tables from other databases/schemas in the same database server. This method can be called to ensure that the additional database/schema is accessible.

For MySQL, PostgreSQL and most other databases no action need to be taken to query data in another database or schema. For SQLite this is however necessary and the database driver for SQLite will override this method.

Parameters

string $database

The database to be attached to the connection.

Return Value

void

protected setPrefix(array|string $prefix)

Set the list of prefixes used by this database connection.

Parameters

array|string $prefix

Either a single prefix, or an array of prefixes.

string prefixTables(string $sql)

Appends a database prefix to all tables in a query.

Queries sent to Drupal should wrap all table names in curly brackets. This function searches for this syntax and adds Drupal's table prefix to all tables, allowing Drupal to coexist with other systems in the same database and/or schema if necessary.

Parameters

string $sql

A string containing a partial or entire SQL query.

Return Value

string

The properly-prefixed string.

string quoteIdentifiers(string $sql)

internal  This method should only be called by database API code.
 

Quotes all identifiers in a query.

Queries sent to Drupal should wrap all unquoted identifiers in square brackets. This function searches for this syntax and replaces them with the database specific identifier. In ANSI SQL this a double quote.

Note that :variable[] is used to denote array arguments but Connection::expandArguments() is always called first.

Parameters

string $sql

A string containing a partial or entire SQL query.

Return Value

string

The string containing a partial or entire SQL query with all identifiers quoted.

tablePrefix(string $table = 'default')

Find the prefix for a table.

This function is for when you want to know the prefix of a table. This is not used in prefixTables due to performance reasons.

Parameters

string $table

(optional) The table to find the prefix for.

array getUnprefixedTablesMap()

Gets a list of individually prefixed table names.

Return Value

array

An array of un-prefixed table names, keyed by their fully qualified table names (i.e. prefix + table_name).

string getFullQualifiedTableName(string $table)

Get a fully qualified table name.

Parameters

string $table

The name of the table in question.

Return Value

string

StatementInterface prepareStatement(string $query, array $options, bool $allow_row_count = FALSE)

Returns a prepared statement given a SQL string.

This method caches prepared statements, reusing them when possible. It also prefixes tables names enclosed in curly braces and, optionally, quotes identifiers enclosed in square brackets.

Parameters

string $query

The query string as SQL, with curly braces surrounding the table names, and square brackets surrounding identifiers.

array $options

An associative array of options to control how the query is run. See the documentation for self::defaultOptions() for details. The content of the 'pdo' key will be passed to the prepared statement.

bool $allow_row_count

(optional) A flag indicating if row count is allowed on the statement object. Defaults to FALSE.

Return Value

StatementInterface

A PDO prepared statement ready for its execute() method.

Exceptions

InvalidArgumentException
DatabaseExceptionWrapper

protected string preprocessStatement(string $query, array $options)

Returns a string SQL statement ready for preparation.

This method replaces table names in curly braces and identifiers in square brackets with platform specific replacements, appropriately escaping them and wrapping them with platform quote characters.

Parameters

string $query

The query string as SQL, with curly braces surrounding the table names, and square brackets surrounding identifiers.

array $options

An associative array of options to control how the query is run. See the documentation for self::defaultOptions() for details.

Return Value

string

A string SQL statement ready for preparation.

Exceptions

InvalidArgumentException

StatementInterface prepareQuery($query, bool $quote_identifiers = TRUE) deprecated

deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Use ::prepareStatement instead.

Prepares a query string and returns the prepared statement.

This method caches prepared statements, reusing them when possible. It also prefixes tables names enclosed in curly-braces and, optionally, quotes identifiers enclosed in square brackets.

Parameters

$query

The query string as SQL, with curly-braces surrounding the table names.

bool $quote_identifiers

(optional) Quote any identifiers enclosed in square brackets. Defaults to TRUE.

Return Value

StatementInterface

A PDO prepared statement ready for its execute() method.

See also

https://www.drupal.org/node/3137786

setTarget(string $target = NULL)

Tells this connection object what its target value is.

This is needed for logging and auditing. It's sloppy to do in the constructor because the constructor for child classes has a different signature. We therefore also ensure that this function is only ever called once.

Parameters

string $target

(optional) The target this connection is for.

string|null getTarget()

Returns the target this connection is associated with.

Return Value

string|null

The target string of this connection, or NULL if no target is set.

setKey(string $key)

Tells this connection object what its key is.

Parameters

string $key

The key this connection is for.

string|null getKey()

Returns the key this connection is associated with.

Return Value

string|null

The key of this connection, or NULL if no key is set.

setLogger(Log $logger)

Associates a logging object with this connection.

Parameters

Log $logger

The logging object we want to use.

Log|null getLogger()

Gets the current logging object for this connection.

Return Value

Log|null

The current logging object for this connection. If there isn't one, NULL is returned.

string makeSequenceName(string $table, string $field)

Creates the appropriate sequence name for a given table and serial field.

This information is exposed to all database drivers, although it is only useful on some of them. This method is table prefix-aware.

Note that if a sequence was generated automatically by the database, its name might not match the one returned by this function. Therefore, in those cases, it is generally advised to use a database-specific way of retrieving the name of an auto-created sequence. For example, PostgreSQL provides a dedicated function for this purpose: pg_get_serial_sequence().

Parameters

string $table

The table name to use for the sequence.

string $field

The field name to use for the sequence.

Return Value

string

A table prefix-parsed string for the sequence name.

string makeComment(string[] $comments)

Flatten an array of query comments into a single comment string.

The comment string will be sanitized to avoid SQL injection attacks.

Parameters

string[] $comments

An array of query comment strings.

Return Value

string

A sanitized comment string.

protected string filterComment(string $comment = '')

Sanitize a query comment string.

Ensure a query comment does not include strings such as "* /" that might terminate the comment early. This avoids SQL injection attacks via the query comment. The comment strings in this example are separated by a space to avoid PHP parse errors.

For example, the comment:

Parameters

string $comment

A query comment string.

Return Value

string

A sanitized version of the query comment string.

StatementInterface|int|string|null query(string|StatementInterface|PDOStatement $query, array $args = [], array $options = [])

Executes a query string against the database.

This method provides a central handler for the actual execution of every query. All queries executed by Drupal are executed as PDO prepared statements.

Parameters

string|StatementInterface|PDOStatement $query

The query to execute. This is a string containing an SQL query with placeholders. (deprecated) An already-prepared instance of StatementInterface or of \PDOStatement may also be passed in order to allow calling code to manually bind variables to a query. In such cases, the content of the $args array will be ignored. It is extremely rare that module code will need to pass a statement object to this method. It is used primarily for database drivers for databases that require special LOB field handling.

array $args

The associative array of arguments for the prepared statement.

array $options

An associative array of options to control how the query is run. The given options will be merged with self::defaultOptions(). See the documentation for self::defaultOptions() for details. Typically, $options['return'] will be set by a default or by a query builder, and should not be set by a user.

Return Value

StatementInterface|int|string|null

This method will return one of the following:

  • If either $options['return'] === self::RETURN_STATEMENT, or $options['return'] is not set (due to self::defaultOptions()), returns the executed statement.
  • If $options['return'] === self::RETURN_AFFECTED, returns the number of rows affected by the query (not the number matched).
  • If $options['return'] === self::RETURN_INSERT_ID, returns the generated insert ID of the last query as a string.
  • If $options['return'] === self::RETURN_NULL, returns NULL.

Exceptions

DatabaseExceptionWrapper
IntegrityConstraintViolationException
InvalidArgumentException

See also

Connection::defaultOptions

protected StatementInterface|int|null handleQueryException(PDOException $e, $query, array $args = [], array $options = [])

Wraps and re-throws any PDO exception thrown by static::query().

Parameters

PDOException $e

The exception thrown by static::query().

$query

The query executed by static::query().

array $args

An array of arguments for the prepared statement.

array $options

An associative array of options to control how the query is run.

Return Value

StatementInterface|int|null

Most database drivers will return NULL when a PDO exception is thrown for a query, but some of them may need to re-run the query, so they can also return a \Drupal\Core\Database\StatementInterface object or an integer.

Exceptions

DatabaseExceptionWrapper
IntegrityConstraintViolationException

protected bool expandArguments(string $query, array $args)

Expands out shorthand placeholders.

Drupal supports an alternate syntax for doing arrays of values. We therefore need to expand them out into a full, executable query string.

Parameters

string $query

The query string to modify.

array $args

The arguments for the query.

Return Value

bool

TRUE if the query was modified, FALSE otherwise.

Exceptions

InvalidArgumentException

string getDriverClass(string $class)

Gets the driver-specific override class if any for the specified class.

Parameters

string $class

The class for which we want the potentially driver-specific class.

Return Value

string

The name of the class that should be used for this driver.

ExceptionHandler exceptionHandler()

Returns the database exceptions handler.

Return Value

ExceptionHandler

The database exceptions handler.

SelectInterface select(string|SelectInterface $table, string $alias = NULL, array $options = [])

Prepares and returns a SELECT query object.

Parameters

string|SelectInterface $table

The base table name or subquery for this query, used in the FROM clause. If a string, the table specified will also be used as the "base" table for query_alter hook implementations.

string $alias

(optional) The alias of the base table of this query.

array $options

An array of options on the query.

Return Value

SelectInterface

An appropriate SelectQuery object for this database connection. Note that it may be a driver-specific subclass of SelectQuery, depending on the driver.

See also

Select

Insert insert(string $table, array $options = [])

Prepares and returns an INSERT query object.

Parameters

string $table

The table to use for the insert statement.

array $options

(optional) An associative array of options to control how the query is run. The given options will be merged with \Drupal\Core\Database\Connection::defaultOptions().

Return Value

Insert

A new Insert query object.

See also

Insert
Connection::defaultOptions

Merge merge(string $table, array $options = [])

Prepares and returns a MERGE query object.

Parameters

string $table

The table to use for the merge statement.

array $options

(optional) An array of options on the query.

Return Value

Merge

A new Merge query object.

See also

Merge

Upsert upsert(string $table, array $options = [])

Prepares and returns an UPSERT query object.

Parameters

string $table

The table to use for the upsert query.

array $options

(optional) An array of options on the query.

Return Value

Upsert

A new Upsert query object.

See also

Upsert

Update update(string $table, array $options = [])

Prepares and returns an UPDATE query object.

Parameters

string $table

The table to use for the update statement.

array $options

(optional) An associative array of options to control how the query is run. The given options will be merged with \Drupal\Core\Database\Connection::defaultOptions().

Return Value

Update

A new Update query object.

See also

Update
Connection::defaultOptions

Delete delete(string $table, array $options = [])

Prepares and returns a DELETE query object.

Parameters

string $table

The table to use for the delete statement.

array $options

(optional) An associative array of options to control how the query is run. The given options will be merged with \Drupal\Core\Database\Connection::defaultOptions().

Return Value

Delete

A new Delete query object.

See also

Delete
Connection::defaultOptions

Truncate truncate(string $table, array $options = [])

Prepares and returns a TRUNCATE query object.

Parameters

string $table

The table to use for the truncate statement.

array $options

(optional) An array of options on the query.

Return Value

Truncate

A new Truncate query object.

See also

Truncate

Schema schema()

Returns a DatabaseSchema object for manipulating the schema.

This method will lazy-load the appropriate schema library file.

Return Value

Schema

The database Schema object for this connection.

Condition condition(string $conjunction)

Prepares and returns a CONDITION query object.

Parameters

string $conjunction

The operator to use to combine conditions: 'AND' or 'OR'.

Return Value

Condition

A new Condition query object.

See also

Condition

string escapeDatabase(string $database)

Escapes a database name string.

Force all database names to be strictly alphanumeric-plus-underscore. For some database drivers, it may also wrap the database name in database-specific escape characters.

Parameters

string $database

An unsanitized database name.

Return Value

string

The sanitized database name.

string escapeTable(string $table)

Escapes a table name string.

Force all table names to be strictly alphanumeric-plus-underscore. Database drivers should never wrap the table name in database-specific escape characters. This is done in Connection::prefixTables(). The database-specific escape characters are added in Connection::setPrefix().

Parameters

string $table

An unsanitized table name.

Return Value

string

The sanitized table name.

See also

Connection::prefixTables
Connection::setPrefix

string escapeField(string $field)

Escapes a field name string.

Force all field names to be strictly alphanumeric-plus-underscore. For some database drivers, it may also wrap the field name in database-specific escape characters.

Parameters

string $field

An unsanitized field name.

Return Value

string

The sanitized field name.

string escapeAlias(string $field)

Escapes an alias name string.

Force all alias names to be strictly alphanumeric-plus-underscore. In contrast to DatabaseConnection::escapeField() / DatabaseConnection::escapeTable(), this doesn't allow the period (".") because that is not allowed in aliases.

Parameters

string $field

An unsanitized alias name.

Return Value

string

The sanitized alias name.

string escapeLike(string $string)

Escapes characters that work as wildcard characters in a LIKE pattern.

The wildcard characters "%" and "_" as well as backslash are prefixed with a backslash. Use this to do a search for a verbatim string without any wildcard behavior.

For example, the following does a case-insensitive query for all rows whose name starts with $prefix:

Parameters

string $string

The string to escape.

Return Value

string

The escaped string.

bool inTransaction()

Determines if there is an active transaction open.

Return Value

bool

TRUE if we're currently in a transaction, FALSE otherwise.

int transactionDepth()

Determines the current transaction depth.

Return Value

int

The current transaction depth.

Transaction startTransaction(string $name = '')

Returns a new DatabaseTransaction object on this connection.

Parameters

string $name

(optional) The name of the savepoint.

Return Value

Transaction

A Transaction object.

See also

Transaction

rollBack(string $savepoint_name = 'drupal_transaction')

Rolls back the transaction entirely or to a named savepoint.

This method throws an exception if no transaction is active.

Parameters

string $savepoint_name

(optional) The name of the savepoint. The default, 'drupal_transaction', will roll the entire transaction back.

Exceptions

TransactionOutOfOrderException
TransactionNoActiveException

pushTransaction(string $name)

Increases the depth of transaction nesting.

If no transaction is already active, we begin a new transaction.

Parameters

string $name

The name of the transaction.

Exceptions

TransactionNameNonUniqueException

See also

Transaction

popTransaction(string $name)

Decreases the depth of transaction nesting.

If we pop off the last transaction layer, then we either commit or roll back the transaction as necessary. If no transaction is active, we return because the transaction may have manually been rolled back.

Parameters

string $name

The name of the savepoint.

Exceptions

TransactionNoActiveException
TransactionCommitFailedException

See also

Transaction

addRootTransactionEndCallback(callable $callback)

Adds a root transaction end callback.

These callbacks are invoked immediately after the transaction has been committed.

It can for example be used to avoid deadlocks on write-heavy tables that do not need to be part of the transaction, like cache tag invalidations.

Another use case is that services using alternative backends like Redis and Memcache cache implementations can replicate the transaction-behavior of the database cache backend and avoid race conditions.

An argument is passed to the callbacks that indicates whether the transaction was successful or not.

Parameters

callable $callback

The callback to invoke.

See also

Connection::doCommit

protected popCommittableTransactions()

Overridden to work around issues to MySQL not supporting transactional DDL.

protected doCommit()

Do the actual commit, invoke post-commit callbacks.

StatementInterface queryRange(string $query, int $from, int $count, array $args = [], array $options = [])

Runs a limited-range query on this database object.

Use this as a substitute for ->query() when a subset of the query is to be returned. User-supplied arguments to the query should be passed in as separate parameters so that they can be properly escaped to avoid SQL injection attacks.

Parameters

string $query

A string containing an SQL query.

int $from

The first result row to return.

int $count

The maximum number of result rows to return.

array $args

(optional) An array of values to substitute into the query at placeholder markers.

array $options

(optional) An array of options on the query.

Return Value

StatementInterface

A database query result resource, or NULL if the query was not executed correctly.

protected string generateTemporaryTableName() deprecated

deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. There is no replacement.

Generates a temporary table name.

Return Value

string

A table name.

See also

https://www.drupal.org/node/3211781

string queryTemporary(string $query, array $args = [], array $options = [])

Runs a SELECT query and stores its results in a temporary table.

Use this as a substitute for ->query() when the results need to stored in a temporary table. Temporary tables exist for the duration of the page request. User-supplied arguments to the query should be passed in as separate parameters so that they can be properly escaped to avoid SQL injection attacks.

Note that if you need to know how many results were returned, you should do a SELECT COUNT(*) on the temporary table afterwards.

Parameters

string $query

A string containing a normal SELECT SQL query.

array $args

(optional) An array of values to substitute into the query at placeholder markers.

array $options

(optional) An associative array of options to control how the query is run. See the documentation for DatabaseConnection::defaultOptions() for details.

Return Value

string

The name of the temporary table.

string driver()

Returns the type of database driver.

This is not necessarily the same as the type of the database itself. For instance, there could be two MySQL drivers, mysql and mysqlMock. This function would return different values for each, but both would return "mysql" for databaseType().

Return Value

string

The type of database driver.

version()

Returns the version of the database server.

clientVersion()

Returns the version of the database client.

bool supportsTransactions() deprecated

deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. All database drivers must support transactions.

Determines if this driver supports transactions.

Return Value

bool

TRUE if this connection supports transactions, FALSE otherwise.

See also

https://www.drupal.org/node/2278745

bool supportsTransactionalDDL()

Determines if this driver supports transactional DDL.

DDL queries are those that change the schema, such as ALTER queries.

Return Value

bool

TRUE if this connection supports transactions for DDL queries, FALSE otherwise.

databaseType()

Returns the name of the PDO driver for this connection.

createDatabase(string $database)

Overrides \Drupal\Core\Database\Connection::createDatabase().

Parameters

string $database

The name of the database to create.

Exceptions

DatabaseNotFoundException

The mapConditionOperator(string $operator)

Gets any special processing requirements for the condition operator.

Some condition types require special processing, such as IN, because the value data they pass in is not a simple value. This is a simple overridable lookup function. Database connections should define only those operators they wish to be handled differently than the default.

Parameters

string $operator

The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.

Return Value

The

extra handling directives for the specified operator, or NULL.

commit()

Throws an exception to deny direct access to transaction commits.

We do not want to allow users to commit transactions at any time, only by destroying the transaction object or allowing it to go out of scope. A direct commit bypasses all of the safety checks we've built on top of PDO's transaction routines.

An nextId($existing_id = 0)

Retrieves a unique ID from a given sequence.

Use this function if for some reason you can't use a serial field. For example, MySQL has no ways of reading of the current value of a sequence and PostgreSQL can not advance the sequence to be larger than a given value. Or sometimes you just need a unique integer.

Parameters

$existing_id

(optional) After a database import, it might be that the sequences table is behind, so by passing in the maximum existing ID, it can be assured that we never issue the same ID.

Return Value

An

integer number larger than any number returned by earlier calls and also larger than the $existing_id if one was passed in.

PDOStatement|false prepare(string $statement, array $driver_options = []) deprecated

deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Database drivers should instantiate \PDOStatement objects by calling \PDO::prepare in their Connection::prepareStatement method instead. \PDO::prepare should not be called outside of driver code.

Prepares a statement for execution and returns a statement object.

Emulated prepared statements do not communicate with the database server so this method does not check the statement.

Parameters

string $statement

This must be a valid SQL statement for the target database server.

array $driver_options

(optional) This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the \PDO::ATTR_CURSOR value to \PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time. Defaults to an empty array.

Return Value

PDOStatement|false

If the database server successfully prepares the statement, returns a \PDOStatement object. If the database server cannot successfully prepare the statement returns FALSE or emits \PDOException (depending on error handling).

Exceptions

PDOException

See also

https://www.php.net/manual/en/pdo.prepare.php
https://www.drupal.org/node/3137786

string|bool quote(string $string, int $parameter_type = \PDO::PARAM_STR)

Quotes a string for use in a query.

Parameters

string $string

The string to be quoted.

int $parameter_type

(optional) Provides a data type hint for drivers that have alternate quoting styles. Defaults to \PDO::PARAM_STR.

Return Value

string|bool

A quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.

See also

\PDO::quote()

static protected string getSQLState(Exception $e)

Extracts the SQLSTATE error from the PDOException.

Parameters

Exception $e

The exception

Return Value

string

The five character error code.

__sleep()

Prevents the database connection from being serialized.

static array createConnectionOptionsFromUrl(string $url, string $root)

internal  This method should only be called from \Drupal\Core\Database\Database::convertDbUrlToConnectionInfo().
 

Creates an array of database connection options from a URL.

Parameters

string $url

The URL.

string $root

The root directory of the Drupal installation. Some database drivers, like for example SQLite, need this information.

Return Value

array

The connection options.

Exceptions

InvalidArgumentException

See also

Database::convertDbUrlToConnectionInfo

static string createUrlFromConnectionOptions(array $connection_options)

internal  This method should only be called from \Drupal\Core\Database\Database::getConnectionInfoAsUrl().
 

Creates a URL from an array of database connection options.

Parameters

array $connection_options

The array of connection options for a database connection. An additional key of 'module' is added by Database::getConnectionInfoAsUrl() for drivers provided my contributed or custom modules for convenience.

Return Value

string

The connection info as a URL.

Exceptions

InvalidArgumentException

See also

Database::getConnectionInfoAsUrl

string getProvider()

Get the module name of the module that is providing the database driver.

Return Value

string

The module name of the module that is providing the database driver, or "core" when the driver is not provided as part of a module.

PagerManagerInterface getPagerManager()

Get the pager manager service, if available.

Return Value

PagerManagerInterface

The pager manager service, if available.

Exceptions

ContainerNotInitializedException

bool isMariaDb()

Determines whether the MySQL distribution is MariaDB or not.

Return Value

bool

Returns TRUE if the distribution is MariaDB, or FALSE if not.

protected string|null getMariaDbVersionMatch()

Gets the MariaDB portion of the server version.

Return Value

string|null

The MariaDB portion of the server version if present, or NULL if not.

protected string getServerVersion()

Gets the server version.

Return Value

string

The PDO server version.

nextIdDelete()

No description