jazzband / django-silk

Silky smooth profiling for Django
MIT License
4.42k stars 333 forks source link

Running queryset.explain will result in an error #597

Open mounirmesselmeni opened 2 years ago

mounirmesselmeni commented 2 years ago

Using djangoql as example which does run queryset.explain will result in a ProgrammingError. Reproducing would be easy by adding a queryset.explain in a view or installing djangoql and try to preform a search in the Django admin.

The generated SQL will contains two explains

syntax error at or near "EXPLAIN"
LINE 1: EXPLAIN EXPLAIN SELECT ...

This is caused by _explain_query and exactly this part

        # currently we cannot use explain() method
        # for queries other than `select`
        prefixed_query = f"{prefix} {q}"
        with connection.cursor() as cur:
            cur.execute(prefixed_query, params)
            result = _unpack_explanation(cur.fetchall())
            return '\n'.join(result)

A possible way to fix this is to check if the SQL starts with explain and skip the check/analyze.

        # currently we cannot use explain() method
        # for queries other than `select`
        # Skip explain queries
        if q.lower().startswith('explain'):
            return None
        prefixed_query = f"{prefix} {q}"
        with connection.cursor() as cur:
            cur.execute(prefixed_query, params)
            result = _unpack_explanation(cur.fetchall())
            return '\n'.join(result)

If that's fine I can prepare a PR for this.

Thank you.