Skip to content

Commit ffe562b

Browse files
authored
Merge pull request pallets-eco#477 from ThiefMaster/no-g
Move query log back to the app context itself
2 parents 86a3deb + 30755c6 commit ffe562b

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

flask_sqlalchemy/__init__.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from threading import Lock
2222

2323
import sqlalchemy
24-
from flask import _app_ctx_stack, abort, current_app, g, request
24+
from flask import _app_ctx_stack, abort, current_app, request
2525
from flask.signals import Namespace
2626
from sqlalchemy import event, inspect, orm
2727
from sqlalchemy.engine.url import make_url
@@ -257,10 +257,12 @@ def after_cursor_execute(
257257
self, conn, cursor, statement, parameters, context, executemany
258258
):
259259
if current_app:
260-
if 'sqlalchemy_queries' not in g:
261-
g.sqlalchemy_queries = []
260+
try:
261+
queries = _app_ctx_stack.top.sqlalchemy_queries
262+
except AttributeError:
263+
queries = _app_ctx_stack.top.sqlalchemy_queries = []
262264

263-
g.sqlalchemy_queries.append(_DebugQueryTuple((
265+
queries.append(_DebugQueryTuple((
264266
statement, parameters, context._query_start_time, _timer(),
265267
_calling_context(self.app_package)
266268
)))
@@ -298,7 +300,7 @@ def get_debug_queries():
298300
query was issued. The exact format is undefined so don't try
299301
to reconstruct filename or function name.
300302
"""
301-
return g.get('sqlalchemy_queries', ())
303+
return getattr(_app_ctx_stack.top, 'sqlalchemy_queries', [])
302304

303305

304306
class Pagination(object):

test_sqlalchemy.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,16 +68,24 @@ def test_query_recording(self):
6868
with self.app.test_request_context():
6969
todo = self.Todo('Test 1', 'test')
7070
self.db.session.add(todo)
71+
self.db.session.flush()
72+
todo.done = True
7173
self.db.session.commit()
7274

7375
queries = fsa.get_debug_queries()
74-
self.assertEqual(len(queries), 1)
76+
self.assertEqual(len(queries), 2)
7577
query = queries[0]
7678
self.assertTrue('insert into' in query.statement.lower())
7779
self.assertEqual(query.parameters[0], 'Test 1')
7880
self.assertEqual(query.parameters[1], 'test')
7981
self.assertTrue('test_sqlalchemy.py' in query.context)
8082
self.assertTrue('test_query_recording' in query.context)
83+
query = queries[1]
84+
self.assertTrue('update' in query.statement.lower())
85+
self.assertEqual(query.parameters[0], 1)
86+
self.assertEqual(query.parameters[1], 1)
87+
self.assertTrue('test_sqlalchemy.py' in query.context)
88+
self.assertTrue('test_query_recording' in query.context)
8189

8290
def test_helper_api(self):
8391
self.assertEqual(self.db.metadata, self.db.Model.metadata)

0 commit comments

Comments
 (0)