Issues

Issue #3081 new

use session.get_bind() for query.__str__()

Mike Bayer
repo owner created an issue

this should be fine. tests should include queries that have no session, sessions with no binds, etc.

diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py
index 5d60c4e..39dc1a1 100644
--- a/lib/sqlalchemy/orm/query.py
+++ b/lib/sqlalchemy/orm/query.py
@@ -2404,6 +2404,11 @@ class Query(object):
             self.session._autoflush()
         return self._execute_and_instances(context)

+    def __str__(self):
+        context = self._compile_context()
+        bind = self._get_bind_args(context, self.session.get_bind)
+        return str(context.statement.compile(bind))
+
     def _connection_from_session(self, **kw):
         conn = self.session.connection(
                         **kw)
@@ -2412,14 +2417,19 @@ class Query(object):
         return conn

     def _execute_and_instances(self, querycontext):
-        conn = self._connection_from_session(
-                        mapper=self._mapper_zero_or_none(),
-                        clause=querycontext.statement,
-                        close_with_result=True)
+        conn = self._get_bind_args(querycontext, self._connection_from_session,
+                                    close_with_result=True)

         result = conn.execute(querycontext.statement, self._params)
         return loading.instances(self, result, querycontext)

+    def _get_bind_args(self, querycontext, fn, **kw):
+        return fn(
+            mapper=self._mapper_zero_or_none(),
+            clause=querycontext.statement,
+            **kw
+        )
+
     @property
     def column_descriptions(self):
         """Return metadata about the columns which would be
@@ -2920,8 +2930,6 @@ class Query(object):
                                     sql.True_._ifnone(context.whereclause),
                                     single_crit)

-    def __str__(self):
-        return str(self._compile_context().statement)

 from ..sql.selectable import ForUpdateArg

Comments (4)

  1. Log in to comment