diff --git a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
index 7e5db5b..07a89d7 100644
--- a/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
+++ b/core/lib/Drupal/Core/Entity/Query/Sql/Query.php
@@ -316,4 +316,22 @@ public function getTables(SelectInterface $sql_query) {
     return new $class($sql_query);
   }

+  /**
+   * Implements the magic __clone method.
+   */
+  public function __toString() {
+    // Clone the query so the prepare and compile stuff doesn't get repeated.
+    // TODO: figure out if this is necessary -- is it ok to call compile() more
+    // than once, e.g. if the query is dumped with this, then more is added to
+    // it?
+    $clone = clone($this);
+
+    $clone->prepare()
+      ->compile()
+      ->addSort()
+      ->finish();
+
+    return (string) $clone->sqlQuery;
+  }
+
 }
