diff --git a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php index 78a4a971911..daf6bd62c00 100644 --- a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php +++ b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php @@ -326,4 +326,28 @@ class Query extends QueryBase implements QueryInterface { return new $class($sql_query); } + /** + * Implements the magic __toString method. + */ + public function __toString() { + // Clone the query so the prepare and compile doesn't get repeated. + $clone = clone($this); + + $clone->prepare() + ->compile() + ->addSort() + ->finish(); + + // Quote arguments so query is able to be run. + $quoted = []; + foreach ($clone->sqlQuery->getArguments() as $key => $value) { + $quoted[$key] = is_null($value) ? 'NULL' : $this->connection->quote($value); + } + + // Replace table name brackets. + $sql = $clone->connection->prefixTables((string) $clone->sqlQuery); + + return strtr($sql, $quoted); + } + } diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php index 21ac9915c44..e96171b2a0e 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php @@ -1201,4 +1201,36 @@ class EntityQueryTest extends EntityKernelTestBase { $this->assertEquals($entity->id(), reset($result)); } + /** + * Tests __toString(). + */ + public function testToString() { + $query = $this->storage->getQuery(); + $group_blue = $query->andConditionGroup()->condition("{$this->figures}.color", ['blue'], 'IN'); + $group_red = $query->andConditionGroup()->condition("{$this->figures}.color", ['red'], 'IN'); + $null_group = $query->andConditionGroup()->notExists("{$this->figures}.color"); + $this->queryResults = $query + ->condition($group_blue) + ->condition($group_red) + ->condition($null_group) + ->sort('id'); + + $figures = $this->figures; + + $expected = <<prefixTables($expected); + $this->assertEquals($expected, (string) $query); + } + }