Connection
class Connection extends Connection (View source)
SQLite implementation of \Drupal\Core\Database\Connection.
Constants
| DATABASE_NOT_FOUND |
Error code for "Unable to open database file" error. |
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 | $transactionalDDLSupport | {@inheritdoc} | |
| 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 | $willRollback | Whether or not the active transaction (if any) will be rolled back. |
|
| static protected | $sqliteConditionOperatorMap | A map of condition operators to SQLite operators. |
|
| protected array | $attachedDatabases | All databases attached to the current database. |
|
| bool | $tableDropped | Whether or not a table has been dropped this request. |
Methods
Constructs a \Drupal\Core\Database\Driver\sqlite\Connection object.
Destructor for the SQLite connection.
Returns the connection information for this connection object.
Allows the connection to access additional databases.
Set the list of prefixes used by this database connection.
Appends a database prefix to all tables in a query.
Get a fully qualified table name.
Returns a prepared statement given a SQL string.
Returns a string SQL statement ready for preparation.
Prepares a query string and returns the prepared statement.
Tells this connection object what its target value is.
Creates the appropriate sequence name for a given table and serial field.
Flatten an array of query comments into a single comment string.
Executes a query string against the database.
Wraps and re-throws any PDO exception thrown by static::query().
Expands out shorthand placeholders.
Gets the driver-specific override class if any for the specified class.
Prepares and returns a SELECT query object.
Prepares and returns an INSERT query object.
Prepares and returns a MERGE query object.
Prepares and returns an UPSERT query object.
Prepares and returns an UPDATE query object.
Prepares and returns a DELETE query object.
Prepares and returns a TRUNCATE query object.
Prepares and returns a CONDITION query object.
Escapes characters that work as wildcard characters in a LIKE pattern.
Returns a new DatabaseTransaction object on this connection.
Rolls back the transaction entirely or to a named savepoint.
Adds a root transaction end callback.
Runs a limited-range query on this database object.
Runs a SELECT query and stores its results in a temporary table.
Returns the type of database driver.
Determines if this driver supports transactional DDL.
Returns the name of the PDO driver for this connection.
Overrides \Drupal\Core\Database\Connection::createDatabase().
Gets any special processing requirements for the condition operator.
Retrieves a unique ID from a given sequence.
Prepares a statement for execution and returns a statement object.
Quotes a string for use in a query.
Creates an array of database connection options from a URL.
Creates a URL from an array of database connection options.
Get the module name of the module that is providing the database driver.
Get the pager manager service, if available.
Gets all the attached databases.
SQLite compatibility implementation for the IF() SQL function.
SQLite compatibility implementation for the GREATEST() SQL function.
SQLite compatibility implementation for the LEAST() SQL function.
SQLite compatibility implementation for the CONCAT() SQL function.
SQLite compatibility implementation for the CONCAT_WS() SQL function.
SQLite compatibility implementation for the SUBSTRING() SQL function.
SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
SQLite compatibility implementation for the RAND() SQL function.
SQLite compatibility implementation for the REGEXP SQL operator.
SQLite compatibility implementation for the LIKE BINARY SQL operator.
Details
__construct(PDO $connection, array $connection_options)
Constructs a \Drupal\Core\Database\Driver\sqlite\Connection object.
static PDO
open(array $connection_options = [])
Opens a PDO connection.
destroy()
deprecated
deprecated
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()
Destructor for the SQLite connection.
We prune empty databases on destruct, but only if tables have been dropped. This is especially needed when running the test suite, which creates and destroy databases several times in a row.
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.
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.
void
attachDatabase(string $database)
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.
protected
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.
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.
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.
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.
array
getUnprefixedTablesMap()
Gets a list of individually prefixed table names.
string
getFullQualifiedTableName(string $table)
Get a fully qualified table name.
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.
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.
StatementInterface
prepareQuery($query, bool $quote_identifiers = TRUE)
deprecated
deprecated
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.
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.
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.
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().
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.
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:
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.
protected StatementInterface|int|null
handleQueryException(PDOException $e, $query, array $args = [], array $options = [])
Wraps and re-throws any PDO exception thrown by static::query().
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.
string
getDriverClass(string $class)
Gets the driver-specific override class if any for the specified class.
ExceptionHandler
exceptionHandler()
Returns the database exceptions handler.
SelectInterface
select(string|SelectInterface $table, string $alias = NULL, array $options = [])
Prepares and returns a SELECT query object.
Insert
insert(string $table, array $options = [])
Prepares and returns an INSERT query object.
Merge
merge(string $table, array $options = [])
Prepares and returns a MERGE query object.
Upsert
upsert(string $table, array $options = [])
Prepares and returns an UPSERT query object.
Update
update(string $table, array $options = [])
Prepares and returns an UPDATE query object.
Delete
delete(string $table, array $options = [])
Prepares and returns a DELETE query object.
Truncate
truncate(string $table, array $options = [])
Prepares and returns a TRUNCATE query object.
Schema
schema()
Returns a DatabaseSchema object for manipulating the schema.
This method will lazy-load the appropriate schema library file.
Condition
condition(string $conjunction)
Prepares and returns a CONDITION query object.
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.
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().
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.
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.
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:
bool
inTransaction()
Determines if there is an active transaction open.
int
transactionDepth()
Determines the current transaction depth.
Transaction
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.
This method throws an exception if no transaction is active.
pushTransaction(string $name)
Increases the depth of transaction nesting.
If no transaction is already active, we begin a new 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.
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.
protected
popCommittableTransactions()
| internal |
Commit all the transaction layers that can commit.
protected
doCommit()
| internal |
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.
protected string
generateTemporaryTableName()
deprecated
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.
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.
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().
version()
Returns the version of the database server.
clientVersion()
Returns the version of the database client.
bool
supportsTransactions()
deprecated
deprecated
Determines if this driver supports transactions.
bool
supportsTransactionalDDL()
Determines if this driver supports transactional DDL.
DDL queries are those that change the schema, such as ALTER queries.
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.
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.
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.
PDOStatement|false
prepare(string $statement, array $driver_options = [])
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.
string|bool
quote(string $string, int $parameter_type = \PDO::PARAM_STR)
Quotes a string for use in a query.
static protected 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.
PagerManagerInterface
getPagerManager()
Get the pager manager service, if available.
array
getAttachedDatabases()
Gets all the attached databases.
static
sqlFunctionIf($condition, $expr1, $expr2 = NULL)
SQLite compatibility implementation for the IF() SQL function.
static
sqlFunctionGreatest()
SQLite compatibility implementation for the GREATEST() SQL function.
static
sqlFunctionLeast()
SQLite compatibility implementation for the LEAST() SQL function.
static
sqlFunctionConcat()
SQLite compatibility implementation for the CONCAT() SQL function.
static
sqlFunctionConcatWs()
SQLite compatibility implementation for the CONCAT_WS() SQL function.
static
sqlFunctionSubstring($string, $from, $length)
SQLite compatibility implementation for the SUBSTRING() SQL function.
static
sqlFunctionSubstringIndex($string, $delimiter, $count)
SQLite compatibility implementation for the SUBSTRING_INDEX() SQL function.
static
sqlFunctionRand($seed = NULL)
SQLite compatibility implementation for the RAND() SQL function.
static
sqlFunctionRegexp($pattern, $subject)
SQLite compatibility implementation for the REGEXP SQL operator.
The REGEXP operator is natively known, but not implemented by default.
static
sqlFunctionLikeBinary($pattern, $subject)
SQLite compatibility implementation for the LIKE BINARY SQL operator.
SQLite supports case-sensitive LIKE operations through the 'case_sensitive_like' PRAGMA statement, but only for ASCII characters, so we have to provide our own implementation with UTF-8 support.