Skip to content

Commit c147480

Browse files
committed
Account for DB aliases when recording transaction state
The logic in SQLPanel.generate_stats() did not properly account for the DB alias when marking transactions as ended. It would always mark the previous query as ending the transaction even if the previous query was from a different DB alias. Update the code to track the last query by alias so that the correct query can be marked as ending the transaction.
1 parent dacef6b commit c147480

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

debug_toolbar/panels/sql/panel.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -178,23 +178,25 @@ def duplicate_key(query):
178178
rgb[nn] = nc
179179
db["rgb_color"] = rgb
180180

181-
trans_ids = {}
182-
trans_id = None
183-
i = 0
181+
# the last query recorded for each DB alias
182+
last_by_alias = {}
184183
for alias, query in self._queries:
185184
query_similar[alias][similar_key(query)] += 1
186185
query_duplicates[alias][duplicate_key(query)] += 1
187186

188187
trans_id = query.get("trans_id")
189-
last_trans_id = trans_ids.get(alias)
190-
191-
if trans_id != last_trans_id:
192-
if last_trans_id:
193-
self._queries[(i - 1)][1]["ends_trans"] = True
194-
trans_ids[alias] = trans_id
195-
if trans_id:
188+
prev_query = last_by_alias.get(alias, {})
189+
prev_trans_id = prev_query.get("trans_id")
190+
191+
# If two consecutive queries for a given DB alias have different
192+
# transaction ID values, a transaction started, finished, or both, so
193+
# annotate the queries as appropriate.
194+
if trans_id != prev_trans_id:
195+
if prev_trans_id is not None:
196+
prev_query["ends_trans"] = True
197+
if trans_id is not None:
196198
query["starts_trans"] = True
197-
if trans_id:
199+
if trans_id is not None:
198200
query["in_trans"] = True
199201

200202
query["alias"] = alias
@@ -222,12 +224,16 @@ def duplicate_key(query):
222224
query["end_offset"] = query["width_ratio"] + query["start_offset"]
223225
width_ratio_tally += query["width_ratio"]
224226
query["stacktrace"] = render_stacktrace(query["stacktrace"])
225-
i += 1
226227

227228
query["trace_color"] = trace_colors[query["stacktrace"]]
228229

229-
if trans_id:
230-
self._queries[(i - 1)][1]["ends_trans"] = True
230+
last_by_alias[alias] = query
231+
232+
# Close out any transactions that were in progress, since there is no
233+
# explicit way to know when a transaction finishes.
234+
for final_query in last_by_alias.values():
235+
if final_query.get("trans_id") is not None:
236+
final_query["ends_trans"] = True
231237

232238
# Queries are similar / duplicates only if there's as least 2 of them.
233239
# Also, to hide queries, we need to give all the duplicate groups an id

0 commit comments

Comments
 (0)