1. Michael Bayer
  2. sqlalchemy
  3. Issues

Issues

Issue #3081 resolved

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

Michael 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 (5)

  1. Michael Bayer reporter
    • The str() call for :class:.Query will now take into account the :class:.Engine to which the :class:.Session is bound, when generating the string form of the SQL, so that the actual SQL that would be emitted to the database is shown, if possible. Previously, only the engine associated with the :class:.MetaData to which the mappings are associated would be used, if present. If no bind can be located either on the :class:.Session or on the :class:.MetaData to which the mappings are associated, then the "default" dialect is used to render the SQL, as was the case previously. fixes #3081

    → <<cset 2a7f37b7b019>>

  2. Log in to comment