@@ -322,21 +322,38 @@ def record_sql(sql, params, cursor=None):
322
322
if hub .get_integration (DjangoIntegration ) is None :
323
323
return
324
324
325
- with capture_internal_exceptions ():
326
- if cursor and hasattr (cursor , "mogrify" ): # psycopg2
327
- real_sql = cursor .mogrify (sql , params )
328
- with capture_internal_exceptions ():
325
+ real_sql = None
326
+ real_params = None
327
+
328
+ try :
329
+ # Prefer our own SQL formatting logic because it's the only one that
330
+ # has proper value trimming.
331
+ real_sql , real_params = format_sql (sql , params )
332
+ if real_sql :
333
+ real_sql = format_and_strip (real_sql , real_params )
334
+ except Exception :
335
+ pass
336
+
337
+ if not real_sql and cursor and hasattr (cursor , "mogrify" ):
338
+ # If formatting failed and we're using psycopg2, it could be that we're
339
+ # looking at a query that uses Composed objects. Use psycopg2's mogrify
340
+ # function to format the query. We lose per-parameter trimming but gain
341
+ # accuracy in formatting.
342
+ #
343
+ # This is intentionally the second choice because we assume Composed
344
+ # queries are not widely used, while per-parameter trimming is
345
+ # generally highly desirable.
346
+ try :
347
+ if cursor and hasattr (cursor , "mogrify" ):
348
+ real_sql = cursor .mogrify (sql , params )
329
349
if isinstance (real_sql , bytes ):
330
350
real_sql = real_sql .decode (cursor .connection .encoding )
331
- else :
332
- real_sql , real_params = format_sql (sql , params )
333
-
334
- if real_params :
335
- try :
336
- real_sql = format_and_strip (real_sql , real_params )
337
- except Exception :
338
- pass
339
- hub .add_breadcrumb (message = real_sql , category = "query" )
351
+ except Exception :
352
+ pass
353
+
354
+ if real_sql :
355
+ with capture_internal_exceptions ():
356
+ hub .add_breadcrumb (message = real_sql , category = "query" )
340
357
341
358
342
359
def install_sql_hook ():
0 commit comments