Drupal 8  8.0.2
Database abstraction layer

Data Structures

class  Connection
 
class  Insert
 
class  Select
 
class  Delete
 
interface  SelectInterface
 
class  Update
 
interface  StatementInterface
 
interface  QueryInterface
 

Functions

 db_query ($query, array $args=array(), array $options=array())
 
 db_query_range ($query, $from, $count, array $args=array(), array $options=array())
 
 db_query_temporary ($query, array $args=array(), array $options=array())
 
 db_insert ($table, array $options=array())
 
 db_merge ($table, array $options=array())
 
 db_update ($table, array $options=array())
 
 db_delete ($table, array $options=array())
 
 db_truncate ($table, array $options=array())
 
 db_select ($table, $alias=NULL, array $options=array())
 
 db_transaction ($name=NULL, array $options=array())
 
 db_set_active ($key= 'default')
 
 db_escape_table ($table)
 
 db_escape_field ($field)
 
 db_like ($string)
 
 db_driver ()
 
 db_close (array $options=array())
 
 db_next_id ($existing_id=0)
 
 db_or ()
 
 db_and ()
 
 db_xor ()
 
 db_condition ($conjunction)
 
 hook_query_alter (Drupal\Core\Database\Query\AlterableInterface $query)
 
 hook_query_TAG_alter (Drupal\Core\Database\Query\AlterableInterface $query)
 

Variables

trait InsertTrait
 

Detailed Description

Allow the use of different database servers using the same code base.

Overview

Drupal's database abstraction layer provides a unified database query API that can query different underlying databases. It is built upon PHP's PDO (PHP Data Objects) database API, and inherits much of its syntax and semantics. Besides providing a unified API for database queries, the database abstraction layer also provides a structured way to construct complex queries, and it protects the database by using good security practices.

For more detailed information on the database abstraction layer, see https://www.drupal.org/developing/api/database.

Migration configuration entities

Any query on Drupal entities or fields should use the Entity Query API. See the entity API topic for more information.

Simple SELECT database queries

For simple SELECT queries that do not involve entities, the Drupal database abstraction layer provides the functions db_query() and db_query_range(), which execute SELECT queries (optionally with range limits) and return result sets that you can iterate over using foreach loops. (The result sets are objects implementing the interface.) You can use the simple query functions for query strings that are not dynamic (except for placeholders, see below), and that you are certain will work in any database engine. See Dynamic SELECT queries below if you have a more complex query, or a query whose syntax would be different in some databases.

As a note, db_query() and similar functions are wrappers on connection object methods. In most classes, you should use dependency injection and the database connection object instead of these wrappers; See Database connection objects below for details.

To use the simple database query functions, you will need to make a couple of modifications to your bare SQL query:

For example, if the query you want to run is:

SELECT e.id, e.title, e.created FROM example e WHERE e.uid = $uid
ORDER BY e.created DESC LIMIT 0, 10;

you would do it like this:

$result = db_query_range('SELECT e.id, e.title, e.created
FROM {example} e
WHERE e.uid = :uid
ORDER BY e.created DESC',
0, 10, array(':uid' => $uid));
foreach ($result as $record) {
// Perform operations on $record->title, etc. here.
}

Note that if your query has a string condition, like:

WHERE e.my_field = 'foo'

when you convert it to placeholders, omit the quotes:

WHERE e.my_field = :my_field
... array(':my_field' => 'foo') ...

Dynamic SELECT queries

For SELECT queries where the simple query API described in Simple SELECT database queries will not work well, you need to use the dynamic query API. However, you should still use the Entity Query API if your query involves entities or fields (see the Entity API topic for more on entity queries).

As a note, db_select() and similar functions are wrappers on connection object methods. In most classes, you should use dependency injection and the database connection object instead of these wrappers; See Database connection objects below for details.

The dynamic query API lets you build up a query dynamically using method calls. As an illustration, the query example from Simple SELECT database queries above would be:

$result = db_select('example', 'e')
->fields('e', array('id', 'title', 'created'))
->condition('e.uid', $uid)
->orderBy('e.created', 'DESC')
->range(0, 10)
->execute();

There are also methods to join to other tables, add fields with aliases, isNull() to have a

WHERE e.foo IS NULL

condition, etc. See https://www.drupal.org/developing/api/database for many more details.

One note on chaining: It is common in the dynamic database API to chain method calls (as illustrated here), because most of the query methods modify the query object and then return the modified query as their return value. However, there are some important exceptions; these methods (and some others) do not support chaining:

INSERT, UPDATE, and DELETE queries INSERT, UPDATE, and DELETE queries need special care in order to behave consistently across databases; you should never use db_query() to run an INSERT, UPDATE, or DELETE query. Instead, use functions db_insert(), db_update(), and db_delete() to obtain a base query on your table, and then add dynamic conditions (as illustrated in Dynamic SELECT queries above).

As a note, db_insert() and similar functions are wrappers on connection object methods. In most classes, you should use dependency injection and the database connection object instead of these wrappers; See Database connection objects below for details.

For example, if your query is:

INSERT INTO example (id, uid, path, name) VALUES (1, 2, 'path', 'Name');

You can execute it via:

$fields = array('id' => 1, 'uid' => 2, 'path' => 'path', 'name' => 'Name');
db_insert('example')
->fields($fields)
->execute();

Transactions

Drupal supports transactions, including a transparent fallback for databases that do not support transactions. To start a new transaction, call

$txn = db_transaction();

The transaction will remain open for as long as the variable $txn remains in scope; when $txn is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope (when all relevant queries have completed successfully).

Example:

function my_transaction_function() {
// The transaction opens here.
$txn = db_transaction();
try {
$id = db_insert('example')
->fields(array(
'field1' => 'mystring',
'field2' => 5,
))
->execute();
my_other_function($id);
return $id;
}
catch (Exception $e) {
// Something went wrong somewhere, so roll back now.
$txn->rollback();
// Log the exception to watchdog.
watchdog_exception('type', $e);
}
// $txn goes out of scope here. Unless the transaction was rolled back, it
// gets automatically committed here.
}
function my_other_function($id) {
// The transaction is still open here.
if ($id % 2 == 0) {
db_update('example')
->condition('id', $id)
->fields(array('field2' => 10))
->execute();
}
}

Database connection objects

The examples here all use functions like db_select() and db_query(), which can be called from any Drupal method or function code. In some classes, you may already have a database connection object in a member variable, or it may be passed into a class constructor via dependency injection. If that is the case, you can look at the code for db_select() and the other functions to see how to get a query object from your connection variable. For example:

$query = $connection->select('example', 'e');

would be the equivalent of

$query = db_select('example', 'e');

if you had a connection object variable $connection available to use. See also the Services and Dependency Injection topic.

See Also
https://www.drupal.org/developing/api/database
Entity API
Schema API

Function Documentation

db_and ( )

Returns a new DatabaseCondition, set to "AND" all conditions together.

Returns
A new Condition object, set to "AND" all conditions together.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Create a object, specifying an AND conjunction: new Condition('AND');
See Also

Referenced by Sql\buildCondition(), UserSelection\entityQueryAlter(), hook_query_TAG_alter(), Access\query(), Search\query(), and SearchQuery\searchExpression().

Here is the caller graph for this function:

db_close ( array  $options = array())

Closes the active database connection.

Parameters
array$optionsAn array of options to control which connection is closed. Only the target key has any meaning in this case.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Use ::closeConnection($target).
See Also
::closeConnection()

Referenced by Tasks\checkBinaryOutput().

Here is the caller graph for this function:

db_condition (   $conjunction)

Returns a new DatabaseCondition, set to the specified conjunction.

Internal API function call. The db_and(), db_or(), and db_xor() functions are preferred.

Parameters
string$conjunctionThe conjunction to use for query conditions (AND, OR or XOR).
Returns
A new Condition object, set to the specified conjunction.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Create a object, specifying the desired conjunction: new Condition($conjunctin);
See Also
db_delete (   $table,
array  $options = array() 
)

Returns a new DeleteQuery object for the active database.

Parameters
string$tableThe table from which to delete.
array$optionsAn array of options to control how the query operates.
Returns
A new Delete object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call delete() on it. For example, $injected_database->delete($table, $options);
See Also
::delete()
::defaultOptions()

Referenced by ShortcutSetStorage\deleteAssignedShortcutSets(), hook_action_delete(), hook_cron(), hook_entity_delete(), hook_ENTITY_TYPE_delete(), hook_field_purge_field(), hook_field_purge_field_storage(), hook_path_delete(), ImportOpmlTest\submitImportForm(), DbLogTest\testFilter(), ContactPersonalTest\testPersonalContactFlood(), DeleteTruncateTest\testSimpleDelete(), ContactSitewideTest\testSiteWideContact(), DeleteTruncateTest\testSpecialColumnDelete(), DeleteTruncateTest\testSubselectDelete(), TrackerTest\testTrackerCronIndexing(), and ShortcutSetStorage\unassignUser().

Here is the caller graph for this function:

db_driver ( )

Retrieves the name of the currently active database driver.

Returns
string The name of the currently active database driver.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call driver() on it. For example, $injected_database->driver($string);
See Also
::driver()
db_escape_field (   $field)

Restricts a dynamic column or constraint name to safe characters.

Only keeps alphanumeric and underscores.

Parameters
string$fieldThe field name to escape.
Returns
string The escaped field name as a string.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call escapeTable() on it. For example, $injected_database->escapeTable($table);
See Also
::escapeField()
db_escape_table (   $table)

Restricts a dynamic table name to safe characters.

Only keeps alphanumeric and underscores.

Parameters
$tableThe table name to escape.
Returns
string The escaped table name as a string.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call escapeTable() on it. For example, $injected_database->escapeTable($table);
See Also
::escapeTable()
db_insert (   $table,
array  $options = array() 
)

Returns a new InsertQuery object for the active database.

Parameters
string$tableThe table into which to insert.
array$optionsAn array of options to control how the query operates.
Returns
A new Insert object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call insert() on it. For example, $injected_database->insert($table, $options);
See Also
::insert()
::defaultOptions()

Referenced by DatabaseTestBase\addSampleData(), SchemaTest\assertFieldAdditionRemoval(), SchemaTest\assertFieldChange(), SchemaTest\assertFieldCharacteristics(), ViewTestBase\enableViewsTestModule(), DatabaseTestBase\ensureSampleDataNull(), hook_entity_insert(), hook_ENTITY_TYPE_insert(), hook_path_insert(), hook_user_logout(), TransactionTest\insertRow(), LocaleUpdateBase\setCurrentTranslations(), ViewKernelTestBase\setUpFixtures(), NodeAccessGrantsCacheContextTest\testCacheContext(), CaseSensitivityTest\testCaseSensitiveInsert(), QueryTest\testConditionOperatorArgumentsSQLInjection(), InsertDefaultsTest\testDefaultEmptyInsert(), InsertDefaultsTest\testDefaultInsert(), InsertDefaultsTest\testDefaultInsertWithFields(), SelectSubqueryTest\testExistsSubquerySelect(), FieldSqlStorageTest\testFieldLoad(), UsageTest\testGetUsage(), HistoryTimestampTest\testHandlers(), InvalidDataTest\testInsertDuplicateData(), InsertTest\testInsertFieldOnlyDefinition(), InsertTest\testInsertLastInsertID(), InsertLobTest\testInsertMultipleBlob(), InsertLobTest\testInsertOneBlob(), InsertTest\testInsertSelectAll(), InsertTest\testInsertSelectFields(), BasicSyntaxTest\testLikeBackslash(), BasicSyntaxTest\testLikeEscape(), InsertTest\testMultiInsert(), NodeQueryAlterTest\testNodeQueryAlterOverride(), CacheTest\testNoneResultCaching(), SelectSubqueryTest\testNotExistsSubquerySelect(), StyleTableTest\testNumericFieldVisible(), SelectTest\testRandomOrder(), RegressionTest\testRegression_310447(), UsageTest\testRemoveUsage(), InsertTest\testRepeatedInsert(), InsertTest\testSimpleInsert(), InsertTest\testSpecialColumnInsert(), CacheTest\testTimeResultCaching(), UpdateLobTest\testUpdateMultipleBlob(), UpdateLobTest\testUpdateOneBlob(), TransactionTest\transactionInnerLayer(), TransactionTest\transactionOuterLayer(), SchemaTest\tryInsert(), and SchemaTest\tryUnsignedInsert().

db_like (   $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.

You must use a query builder like db_select() in order to use db_like() on all supported database systems. Using db_like() with db_query() or db_query_range() is not supported.

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

$result = db_select('person', 'p')
->fields('p')
->condition('name', db_like($prefix) . '%', 'LIKE')
->execute()
->fetchAll();

Backslash is defined as escape character for LIKE patterns in DatabaseCondition::mapConditionOperator().

Parameters
string$stringThe string to escape.
Returns
string The escaped string.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call escapeLike() on it. For example, $injected_database->escapeLike($string);
See Also
::escapeLike()

Referenced by StringDatabaseStorage\dbStringSelect(), EntityReference\query(), BasicSyntaxTest\testLikeBackslash(), and BasicSyntaxTest\testLikeEscape().

Here is the caller graph for this function:

db_merge (   $table,
array  $options = array() 
)

Returns a new MergeQuery object for the active database.

Parameters
string$tableName of the table to associate with this query.
array$optionsAn array of options to control how the query operates.
Returns
A new Merge object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call merge() on it. For example, $injected_database->merge($table, $options);
See Also
::merge()
::defaultOptions()

Referenced by ShortcutSetStorage\assignUser(), hook_entity_predelete(), hook_ENTITY_TYPE_predelete(), GarbageCollectionTest\testGarbageCollection(), MergeTest\testInvalidMerge(), MergeTest\testMergeInsert(), MergeTest\testMergeInsertWithoutUpdate(), MergeTest\testMergeUpdate(), MergeTest\testMergeUpdateExcept(), MergeTest\testMergeUpdateExplicit(), MergeTest\testMergeUpdateExpression(), and MergeTest\testMergeUpdateWithoutUpdate().

Here is the caller graph for this function:

db_next_id (   $existing_id = 0)

Retrieves a unique id.

Use this function if for some reason you can't use a serial field. Using a serial field is preferred, and InsertQuery::execute() returns the value of the last ID inserted.

Parameters
int$existing_idAfter a database import, it might be that the sequences table is behind, so by passing in a minimum ID, it can be assured that we never issue the same ID.
Returns
int An integer number larger than any number returned before for this sequence.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call nextId() on it. For example, $injected_database->nextId($existing_id);
See Also
::nextId()

Referenced by NextIdTest\testDbNextId().

Here is the caller graph for this function:

db_or ( )

Returns a new DatabaseCondition, set to "OR" all conditions together.

Returns
A new Condition object, set to "OR" all conditions together.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Create a object, specifying an OR conjunction: new Condition('OR');
See Also

Referenced by Sql\buildCondition(), StringDatabaseStorage\dbStringSelect(), UserSelection\entityQueryAlter(), hook_query_TAG_alter(), SearchQuery\parseSearchExpression(), SearchQuery\prepareAndNormalize(), UserUid\query(), Access\query(), Current\query(), TaxonomyIndexTidDepth\query(), Search\query(), EntityReference\query(), SelectComplexTest\testNestedConditions(), and UpdateComplexTest\testOrConditionUpdate().

Here is the caller graph for this function:

db_query (   $query,
array  $args = array(),
array  $options = array() 
)

Executes an arbitrary query string against the active database.

Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.

Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.

Parameters
string | \Drupal\Core\Database\StatementInterface$queryThe prepared statement query to run. Although it will accept both named and unnamed placeholders, named placeholders are strongly preferred as they are more self-documenting. If the argument corresponding to a placeholder is an array of values to be expanded (for example, with an IN query), the placeholder should be named with a trailing bracket like :example[].
array$argsAn array of values to substitute into the query. If the query uses named placeholders, this is an associative array in any order. If the query uses unnamed placeholders (?), this is an indexed array and the order must match the order of placeholders in the query string.
array$optionsAn array of options to control how the query operates.
Returns
A prepared statement object, already executed.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call query() on it. For example, $injected_database->query($query, $args, $options);
See Also
::query()
::defaultOptions()

Referenced by EntityApiTest\assertCRUD(), TransactionTest\assertRowAbsent(), TransactionTest\assertRowPresent(), SessionHttpsTest\assertSessionIds(), LocaleUpdateBase\assertTranslation(), callback_batch_operation(), Tasks\checkBinaryOutput(), Tasks\checkBinaryOutputSuccess(), Tasks\checkEncoding(), ShortcutSetStorage\countAssignedUsers(), AggregatorTestBase\createFeed(), ForumTest\createForum(), Schema\findTables(), DBLogResource\get(), FileFieldTestBase\getLastFileId(), PathAliasTest\getPID(), DbDumpTest\getTableIndexes(), DbDumpTest\getTableSchema(), VocabularyStorage\getToplevelTids(), NodeCreationTest\getWatchdogIdsForFailedExplicitRollback(), NodeCreationTest\getWatchdogIdsForTestExceptionRollback(), hook_cron(), hook_node_search_result(), hook_node_update_index(), ImportOpmlTest\submitImportForm(), ForumTest\testAddOrphanTopic(), QueryTest\testArrayArgumentsSQLInjection(), QueryTest\testArraySubstitution(), FeedParserTest\testAtomSample(), UpdateComplexTest\testBetweenConditionUpdate(), CaseSensitivityTest\testCaseSensitiveInsert(), TransactionTest\testCommittedTransaction(), BasicSyntaxTest\testConcatFields(), BasicSyntaxTest\testConcatLiterals(), BasicSyntaxTest\testConcatWsFields(), BasicSyntaxTest\testConcatWsLiterals(), ConnectionFailureTest\testConnectionFailureLogging(), AggregatorCronTest\testCron(), DbLogTest\testDBLogAddAndClear(), InsertDefaultsTest\testDefaultEmptyInsert(), InsertDefaultsTest\testDefaultInsert(), InsertDefaultsTest\testDefaultInsertWithFields(), DeleteFeedTest\testDeleteFeed(), BlockContentTranslationUITest\testDisabledBundle(), NodeTranslationUITest\testDisabledBundle(), SessionTest\testEmptySessionID(), LocaleUpdateTest\testEnableLanguage(), LoggingTest\testEnableLogging(), LoggingTest\testEnableMultiConnectionLogging(), LoggingTest\testEnableMultiLogging(), LoggingTest\testEnableTargetLogging(), LoggingTest\testEnableTargetLoggingNoTarget(), SelectPagerDefaultTest\testEvenPagerQuery(), UpdateTest\testExpressionUpdate(), BlockContentCreationTest\testFailedBlockCreation(), GarbageCollectionTest\testGarbageCollection(), InstallTest\testGetSchemaAtInstallTime(), BlockContentSaveTest\testImport(), UpdateComplexTest\testInConditionUpdate(), SchemaTest\testIndexLength(), InvalidDataTest\testInsertDuplicateData(), InsertTest\testInsertFieldOnlyDefinition(), InsertLobTest\testInsertMultipleBlob(), InsertLobTest\testInsertOneBlob(), InsertTest\testInsertSelectAll(), InsertTest\testInsertSelectFields(), IpAddressBlockingTest\testIPAddressValidation(), UpdateComplexTest\testLikeConditionUpdate(), LargeQueryTest\testMaxAllowedPacketQueryTruncating(), MergeTest\testMergeInsert(), MergeTest\testMergeInsertWithoutUpdate(), MergeTest\testMergeUpdate(), MergeTest\testMergeUpdateExcept(), MergeTest\testMergeUpdateExplicit(), MergeTest\testMergeUpdateExpression(), MergeTest\testMergeUpdateWithoutUpdate(), UpdateTest\testMultiGTUpdate(), InsertTest\testMultiInsert(), UpdateTest\testMultiUpdate(), NodeAccessBaseTableTest\testNodeAccessBasic(), NodeAccessRecordsTest\testNodeAccessRecords(), NodeRevisionPermissionsTest\testNodeRevisionAccessAnyType(), NodeRevisionPermissionsTest\testNodeRevisionAccessPerType(), SaveUploadTest\testNormal(), UpdateComplexTest\testNotInConditionUpdate(), QueryTest\testNumericExpressionSubstitution(), SelectPagerDefaultTest\testOddPagerQuery(), UpdateComplexTest\testOrConditionUpdate(), ContactPersonalTest\testPersonalContactFlood(), LocalePluralFormatTest\testPluralEditDateFormatter(), LocalePluralFormatTest\testPluralEditExport(), UpdateTest\testPrimaryKeyUpdate(), FetchTest\testQueryFetchArray(), FetchTest\testQueryFetchBoth(), FetchTest\testQueryFetchClass(), FetchTest\testQueryFetchCol(), FetchTest\testQueryFetchDefault(), FetchTest\testQueryFetchNum(), FetchTest\testQueryFetchObject(), SelectTest\testRandomOrder(), RangeQueryTest\testRangeQuery(), RegressionTest\testRegression_310447(), RelationshipTest\testRelationshipQuery(), RelationshipTest\testRelationshipRender(), InsertTest\testRepeatedInsert(), NodeRevisionsAllTest\testRevisions(), NodeRevisionsTest\testRevisions(), FetchTest\testRowCount(), QueryTest\testScalarSubstitution(), SchemaTest\testSchema(), DbDumpTest\testScriptLoad(), SearchNodeUpdateAndDeletionTest\testSearchIndexUpdateOnNodeDeletion(), SessionTest\testSessionWrite(), DeleteTruncateTest\testSimpleDelete(), InsertTest\testSimpleInsert(), UpdateTest\testSimpleNullUpdate(), UpdateTest\testSimpleUpdate(), ContactSitewideTest\testSiteWideContact(), DeleteTruncateTest\testSpecialColumnDelete(), InsertTest\testSpecialColumnInsert(), UpdateTest\testSpecialColumnUpdate(), LocaleImportFunctionalTest\testStandalonePoFile(), LocaleStringTest\testStringCRUDAPI(), DeleteTruncateTest\testSubselectDelete(), UpdateComplexTest\testSubSelectUpdate(), TermIndexTest\testTaxonomyIndex(), DbLogTest\testTemporaryUser(), PathTaxonomyTermTest\testTermAlias(), TransactionTest\testTransactionRollBackNotSupported(), TransactionTest\testTransactionRollBackSupported(), TermTranslationUITest\testTranslationUI(), DeleteTruncateTest\testTruncate(), UpdateComplexTest\testUpdateExpression(), UpdateFeedItemTest\testUpdateFeedItem(), UpdateLobTest\testUpdateMultipleBlob(), UpdateLobTest\testUpdateOneBlob(), UpdateComplexTest\testUpdateOnlyExpression(), UserInstallTest\testUserInstall(), UpdateTest\testWhereAndConditionUpdate(), UpdateTest\testWhereUpdate(), AggregatorTestBase\uniqueFeed(), AggregatorTestBase\updateAndDelete(), AggregatorTestBase\updateFeedItems(), and ImportOpmlTest\validateImportFormFields().

db_query_range (   $query,
  $from,
  $count,
array  $args = array(),
array  $options = array() 
)

Executes a query against the active database, restricted to a range.

Parameters
string$queryThe prepared statement query to run. Although it will accept both named and unnamed placeholders, named placeholders are strongly preferred as they are more self-documenting.
$fromThe first record from the result set to return.
$countThe number of records to return from the result set.
array$argsAn array of values to substitute into the query. If the query uses named placeholders, this is an associative array in any order. If the query uses unnamed placeholders (?), this is an indexed array and the order must match the order of placeholders in the query string.
array$optionsAn array of options to control how the query operates.
Returns
A prepared statement object, already executed.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call queryRange() on it. For example, $injected_database->queryRange($query, $from, $count, $args, $options);
See Also
::queryRange()
::defaultOptions()

Referenced by callback_batch_operation(), AggregatorTestBase\getDefaultFeedItemCount(), StorageTest\testImmutableFormLegacyProtection(), RangeQueryTest\testRangeQuery(), and DbLogResourceTest\testWatchdog().

Here is the caller graph for this function:

db_query_temporary (   $query,
array  $args = array(),
array  $options = array() 
)

Executes a SELECT query string and saves the result set to a temporary table.

The execution of the query string happens against the active database.

Parameters
string$queryThe prepared SELECT statement query to run. Although it will accept both named and unnamed placeholders, named placeholders are strongly preferred as they are more self-documenting.
array$argsAn array of values to substitute into the query. If the query uses named placeholders, this is an associative array in any order. If the query uses unnamed placeholders (?), this is an indexed array and the order must match the order of placeholders in the query string.
array$optionsAn array of options to control how the query operates.
Returns
The name of the temporary table.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call queryTemporary() on it. For example, $injected_database->queryTemporary($query, $args, $options);
See Also
::queryTemporary()
::defaultOptions()

Referenced by DatabaseTestController\dbQueryTemporary(), and TemporaryQueryTest\testTemporaryQuery().

Here is the caller graph for this function:

db_select (   $table,
  $alias = NULL,
array  $options = array() 
)

Returns a new SelectQuery object for the active database.

Parameters
string | \Drupal\Core\Database\Query\SelectInterface$tableThe base table for this query. May be a string or another SelectInterface object. If a SelectInterface object is passed, it will be used as a subselect.
string$alias(optional) The alias for the base table of this query.
array$options(optional) An array of options to control how the query operates.
Returns
A new Select object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call select() on it. For example, $injected_database->select($table, $alias, $options);
See Also
::select()
::defaultOptions()

Referenced by SearchMatchTest\_testQueries(), SearchMultilingualEntityTest\assertDatabaseCounts(), SchemaTest\assertFieldChange(), SchemaTest\assertFieldCharacteristics(), ModuleTestBase\assertLogMessage(), DatabaseTestForm\buildForm(), ActiveTopicsBlock\buildForumQuery(), NewTopicsBlock\buildForumQuery(), SearchQuery\countQuery(), TemporaryQueryTest\countTableRows(), DatabaseTestController\dbQueryTemporary(), ShortcutSetStorage\getAssignedToUser(), BookOutlineStorage\getBookSubtree(), TermStorage\getNodeTerms(), hook_entity_predelete(), hook_ENTITY_TYPE_predelete(), DatabaseTestController\pagerQueryEven(), DatabaseTestController\pagerQueryOdd(), UserUid\query(), TaxonomyIndexTidDepth\query(), NodeTermData\query(), PagerTestController\queryParameters(), Search\queryParseSearchExpression(), UsageTest\testAddUsage(), AlterTest\testAlterChangeConditional(), AlterTest\testAlterChangeFields(), AlterTest\testAlterExpression(), AlterTest\testAlterRemoveRange(), AlterTest\testAlterWithJoin(), QueryTest\testArrayArgumentsSQLInjection(), JoinTest\testBasePlugin(), QueryTest\testConditionOperatorArgumentsSQLInjection(), SelectSubqueryTest\testConditionSubquerySelect(), NodeAdminTest\testContentAdminSort(), SelectComplexTest\testCountQuery(), SelectComplexTest\testCountQueryDistinct(), SelectComplexTest\testCountQueryFieldRemovals(), SelectComplexTest\testCountQueryGroupBy(), SelectComplexTest\testCountQueryRemovals(), SelectComplexTest\testDefaultJoin(), StatisticsAdminTest\testDeleteNode(), SelectComplexTest\testDistinct(), SelectPagerDefaultTest\testElementNumbers(), SelectTest\testEmptyInCondition(), JoinTest\testExamplePlugin(), SelectSubqueryTest\testExistsSubquerySelect(), StatisticsAdminTest\testExpiredLogs(), TaggingTest\testExtenderHasAllTags(), TaggingTest\testExtenderHasAnyTag(), TaggingTest\testExtenderHasTag(), BlockContentCreationTest\testFailedBlockCreation(), SelectSubqueryTest\testFromSubquerySelect(), SelectSubqueryTest\testFromSubquerySelectWithLimit(), SelectComplexTest\testGroupBy(), SelectComplexTest\testGroupByAndHaving(), TaggingTest\testHasAllTags(), TaggingTest\testHasAnyTag(), TaggingTest\testHasTag(), SelectComplexTest\testHavingCountQuery(), SelectPagerDefaultTest\testHavingPagerQuery(), SelectPagerDefaultTest\testInnerPagerQuery(), InvalidDataTest\testInsertDuplicateData(), InsertTest\testInsertSelectAll(), InsertTest\testInsertSelectFields(), SelectTest\testInvalidSelectCount(), SelectTest\testIsNotNullCondition(), SelectTest\testIsNullCondition(), SelectComplexTest\testJoinSubquery(), SelectSubqueryTest\testJoinSubquerySelect(), SelectComplexTest\testJoinTwice(), SelectComplexTest\testLeftOuterJoin(), BasicSyntaxTest\testLikeBackslash(), BasicSyntaxTest\testLikeEscape(), TaggingTest\testMetaData(), SearchMultilingualEntityTest\testMultilingualSearch(), SelectComplexTest\testNestedConditions(), NodeAccessLanguageAwareTest\testNodeAccessLanguageAware(), NodeAccessLanguageAwareCombinationTest\testNodeAccessLanguageAwareCombination(), NodeAccessLanguageTest\testNodeAccessQueryTag(), NodeQueryAlterTest\testNodeQueryAlterLowLevelEditAccess(), NodeQueryAlterTest\testNodeQueryAlterLowLevelNoAccess(), NodeQueryAlterTest\testNodeQueryAlterLowLevelWithAccess(), NodeQueryAlterTest\testNodeQueryAlterOverride(), SelectSubqueryTest\testNotExistsSubquerySelect(), SelectTest\testNullCondition(), SelectTest\testRandomOrder(), SelectComplexTest\testRange(), UsageTest\testRemoveUsage(), NodeRevisionsTest\testRevisions(), SelectCloneTest\testSelectConditionSubQueryCloning(), SelectTest\testSelectDuplicateAlias(), SelectComplexTest\testSelectWithRowCount(), SerializeQueryTest\testSerializeQuery(), AlterTest\testSimpleAlter(), AlterTest\testSimpleAlterSubquery(), SelectTest\testSimpleComment(), SelectTest\testSimpleSelect(), SelectTest\testSimpleSelectAllFields(), SelectTest\testSimpleSelectConditional(), SelectTest\testSimpleSelectExpression(), SelectTest\testSimpleSelectExpressionMultiple(), SelectOrderedTest\testSimpleSelectMultiOrdered(), SelectTest\testSimpleSelectMultipleFields(), SelectOrderedTest\testSimpleSelectOrdered(), SelectOrderedTest\testSimpleSelectOrderedDesc(), DeleteTruncateTest\testSubselectDelete(), UpdateComplexTest\testSubSelectUpdate(), DatabaseTestController\testTablesort(), DatabaseTestController\testTablesortFirst(), SelectTest\testUnion(), SelectTest\testUnionAll(), SelectTest\testUnionCount(), UserDeleteTest\testUserDeleteMultiple(), and SelectTest\testVulnerableComment().

db_set_active (   $key = 'default')

Sets a new active database.

Parameters
$keyThe key in the $databases array to set as the default database.
Returns
string|null The key of the formerly active database.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Use ::setActiveConnection().

Referenced by Tasks\connect(), and LoggingTest\testEnableMultiConnectionLogging().

Here is the caller graph for this function:

db_transaction (   $name = NULL,
array  $options = array() 
)

Returns a new transaction object for the active database.

Parameters
string$nameOptional name of the transaction.
array$optionsAn array of options to control how the transaction operates:
  • target: The database target name.
Returns
A new Transaction object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call startTransaction() on it. For example, $injected_database->startTransaction($name);
See Also
::startTransaction()
::defaultOptions()

Referenced by MenuRouterRebuildSubscriber\menuLinksRebuild(), TransactionTest\testTransactionStacking(), TransactionTest\testTransactionWithDdlStatement(), TransactionTest\transactionInnerLayer(), and TransactionTest\transactionOuterLayer().

Here is the caller graph for this function:

db_truncate (   $table,
array  $options = array() 
)

Returns a new TruncateQuery object for the active database.

Parameters
string$tableThe table from which to truncate.
array$optionsAn array of options to control how the query operates.
Returns
A new Truncate object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call truncate() on it. For example, $injected_database->truncate($table, $options);
See Also
::truncate()
::defaultOptions()

Referenced by SchemaTest\assertFieldChange(), TransactionTest\cleanUp(), and DeleteTruncateTest\testTruncate().

Here is the caller graph for this function:

db_update (   $table,
array  $options = array() 
)

Returns a new UpdateQuery object for the active database.

Parameters
string$tableThe table to update.
array$optionsAn array of options to control how the query operates.
Returns
A new Update object for this connection.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call update() on it. For example, $injected_database->update($table, $options);
See Also
::update()
::defaultOptions()

Referenced by UsageTest\createTempFiles(), hook_ENTITY_TYPE_update(), hook_entity_update(), hook_path_update(), hook_user_cancel(), UserPasswordResetTest\setUp(), UpdateComplexTest\testBetweenConditionUpdate(), NodeAdminTest\testContentAdminSort(), UserPictureTest\testCreateDeletePicture(), AggregatorCronTest\testCron(), UpdateTest\testExpressionUpdate(), UpdateComplexTest\testInConditionUpdate(), DeleteTest\testInUse(), UpdateComplexTest\testLikeConditionUpdate(), UpdateTest\testMultiGTUpdate(), SearchMultilingualEntityTest\testMultilingualSearch(), UpdateTest\testMultiUpdate(), UpdateComplexTest\testNotInConditionUpdate(), UpdateComplexTest\testOrConditionUpdate(), UpdateTest\testPrimaryKeyUpdate(), NodeBlockFunctionalTest\testRecentNodeBlock(), UserPasswordResetTest\testResetImpersonation(), NodeRevisionsAllTest\testRevisions(), NodeRevisionsTest\testRevisions(), UpdateTest\testSimpleNullUpdate(), UpdateTest\testSimpleUpdate(), UpdateTest\testSpecialColumnUpdate(), UpdateComplexTest\testSubSelectUpdate(), UpdateTest\testUpdateAffectedRows(), LocaleUpdateCronTest\testUpdateCron(), UpdateComplexTest\testUpdateExpression(), UpdateFeedItemTest\testUpdateFeedItem(), UpdateLobTest\testUpdateMultipleBlob(), UpdateLobTest\testUpdateOneBlob(), UpdateComplexTest\testUpdateOnlyExpression(), UserCancelTest\testUserCancelUid1(), TempStoreDatabaseTest\testUserTempStore(), UpdateTest\testWhereAndConditionUpdate(), and UpdateTest\testWhereUpdate().

Here is the caller graph for this function:

db_xor ( )

Returns a new DatabaseCondition, set to "XOR" all conditions together.

Returns
A new Condition object, set to "XOR" all conditions together.
Deprecated:
as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Create a object, specifying an XOR conjunction: new Condition('XOR');
See Also
hook_query_alter ( Drupal\Core\Database\Query\AlterableInterface  $query)

Perform alterations to a structured query.

Structured (aka dynamic) queries that have tags associated may be altered by any module before the query is executed.

Parameters
$queryA Query object describing the composite parts of a SQL query.
See Also
hook_query_TAG_alter()
node_query_node_access_alter()
AlterableInterface
SelectInterface
hook_query_TAG_alter ( Drupal\Core\Database\Query\AlterableInterface  $query)

Perform alterations to a structured query for a given tag.

Parameters
$queryAn Query object describing the composite parts of a SQL query.
See Also
hook_query_alter()
node_query_node_access_alter()
AlterableInterface
SelectInterface

References Drupal\currentUser(), db_and(), and db_or().

Here is the call graph for this function:

Variable Documentation

trait InsertTrait
Initial value:
{
protected $table

Provides common functionality for INSERT and UPSERT queries.