Opened 8 months ago

Closed 8 months ago

#35388 closed New feature (needsinfo)

force_debug_cursor, assertNumQueries(), and CaptureQueriesContext() doesn't work in async.

Reported by: James Ostrander Owned by: nobody
Component: Database layer (models, ORM) Version: 4.2
Severity: Normal Keywords: connection, db, orm, force_debug_cursor, async
Cc: James Ostrander Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by James Ostrander)

Django version: 4.2.11
Python version: 3.12

Settings:

DEBUG=False
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "default": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "django.db.backends": {
            "handlers": ["default"],
            "level": "DEBUG",
            "propagate": False,
        },
    },
}

For Pytest, where DEBUG=False, this removes a means of enabling query logging via override.

SYNC VIEW (WORKING):

def query_test_sync(request: HttpRequest) -> HttpResponse:
    from django.db import connection

    connection.force_debug_cursor = True

    a = Thing.objects.first()
    return HttpResponse(f"First thing: {a.id}")

Log:

web-1       | [18/Apr/2024 14:48:35] "GET /test_query_sync/ HTTP/1.1" 200 31
web-1       | (0.001) SELECT "thing_thing"."name", "thing_thing"."id" FROM "thing_thing" ORDER BY "thing_thing"."id" ASC LIMIT 1; args=(); alias=default

ASYNC VIEW (NOT WORKING):

async def query_test_async(request: HttpRequest) -> HttpResponse:
    from django.db import connection

    connection.force_debug_cursor = True

    a = await Thing.objects.afirst()
    return HttpResponse(f"First thing: {a.id}")

Log:

web-1       | [18/Apr/2024 15:00:29] "GET /test_query_async/ HTTP/1.1" 200 31

Also worth noting: CaptureQueriesContext does not work in an async context.

Change History (5)

comment:1 by James Ostrander, 8 months ago

Description: modified (diff)

comment:2 by James Ostrander, 8 months ago

Version: 5.04.2

comment:3 by James Ostrander, 8 months ago

If the fix is something simple, I would be happy to submit a PR.

comment:4 by James Ostrander, 8 months ago

Description: modified (diff)

in reply to:  3 comment:5 by Mariusz Felisiak, 8 months ago

Keywords: async added
Resolution: needsinfo
Status: newclosed
Summary: `force_debug_cursor` does nothing in asyncforce_debug_cursor, assertNumQueries(), and CaptureQueriesContext() doesn't work in async.
Type: BugNew feature

Replying to James Ostrander:

If the fix is something simple, ...

No, it's not. I tried really hard few months ago and it's probably not doable, check out comments:

Marking as "needsinfo", because, as far as I'm aware there is a way to move it forward. We can reconsider this decision only if someone provides PoC.

Note: See TracTickets for help on using tickets.
Back to Top