Change record status: 
Project: 
Introduced in branch: 
9.4.x
Introduced in version: 
9.4.0
Description: 

The 'return' query option and the Database::RETURN_* constants are deprecated. In Drupal 11, they will be removed and Connection::query() will always return a StatementInterface object.

In general, Connection::query() should not be used for data manipulation operations (INSERT, DELETE, UPDATE, UPSERT, MERGE, TRUNCATE); Drupal's Database API provides dynamic queries for these purposes, that allow database abstraction.

A new Connection::lastInsertId() method is available in the edge cases where the use Connection::query() is needed for INSERT; in that case, Connection::lastInsertId() will allow extraction the last insert id value from the connection.

For UPDATE and other operations, since #3177660: Remove public properties from StatementInterface implementations, Database::RETURN_AFFECTED should not be used; enable row counting by passing the appropriate argument to the constructor instead.

Example from MySql's Connection::nextId() below.

BEFORE:

      $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', [], ['return' => Database::RETURN_INSERT_ID]);

AFTER:

      $this->query('INSERT INTO {sequences} () VALUES ()');
      $new_id = $this->lastInsertId();
Impacts: 
Module developers

Comments

shenzhuxi’s picture

Can anyone give an example for the replacement of Database::RETURN_AFFECTED?
Is prepareStatement(string $query, array $options, bool $allow_row_count = TRUE) the only way?

miiimooo’s picture

I was wondering the same. After a bit of experimentation this worked (based on your suggestion as a practical example):

$query = "UPDATE {node} n SET n.langcode = 'fr' where n.nid=1";
$stm = Drupal::database()->prepareStatement($query, [], TRUE);
$query = Drupal::database()->query($stm);
$affected = $query->rowCount();

If there is another way I would be interested to hear.

pfrenssen’s picture

You mixed up the query and prepared statement ;) This works:

$query = "UPDATE {node} n SET n.langcode = 'fr' where n.nid=1";
$statement = \Drupal::database()->prepareStatement($query, [], TRUE);
$statement->execute();
$affected_rows = $statement->rowCount();