Skip to main content

Decorator for measuring the time and number of database queries

Project description

Class to simplify the search for slow and suboptimal sql queries to the database in django projects.

Project Status
CI/CD Latest Release
Quality Coverage
Package PyPI - Version PyPI - Support Python Versions Project PyPI - Downloads
Meta types - Mypy License - MIT code style - Ruff

About class

  • Class allows you to track any sql queries that are executed inside the body of a loop, a decorated function, or a context manager, the body can be executed a specified number of times to get the average query execution time.

  • The class allows you to display formatted output data containing brief information about the current iteration of the measurement, display sql queries and explain information on them, as well as summary information containing data on all measurements.

Do not use the class inside the business logic of your application, this will greatly slow down the execution of the queries, the class is intended only for the test environment.

Install

  1. Install package
    pip install capture-db-queries
    

About class parameters

All parameters are purely optional.

  • Optional parameters:
    • assert_q_count: The expected number of database queries during all number_runs, otherwise an exception will be raised: "AssertionError: N not less than or equal to N queries".
    • number_runs: The number of runs of the decorated function or test for loop.
    • verbose: Displaying the final results of test measurements within all number_runs.
    • advanced_verb: Displaying the result of each test measurement.
    • auto_call_func: Autorun of the decorated function. (without passing arguments to the function, since the launch takes place inside the class).
    • queries: Displaying colored and formatted SQL queries to the database.
    • explain: Displaying explain information about each query. (has no effect on the original query).
    • explain_opts: Parameters for explain. (for more information about the parameters for explain, see the documentation for your DBMS).
    • connection: Connecting to your database, by default: django.db.connection

> WARNING: If you use pytest-xdist and run the test with the -n <workers> flag, the results will not be reflected in the terminal. Remove the -n <workers> flag to display them or use --capture=tee-sys -rP parameters.

Usage examples

from capture_db_queries import CaptureQueries
for ctx in CaptureQueries(number_runs=2, advanced_verb=True):
    response = self.client.get(url)

>>> Test 1 | Queries count: 10 | Execution time: 0.04s
>>> Test 2 | Queries count: 10 | Execution time: 0.04s
>>> Tests count: 2  |  Total queries count: 20  |  Total execution time: 0.08s  |  Median time one test is: 0.041s  |  Vendor: sqlite

OR

@CaptureQueries(number_runs=2, advanced_verb=True)
def test_request():
    response = self.client.get(url)

>>> Test 1 | Queries count: 10 | Execution time: 0.04s
>>> Test 2 | Queries count: 10 | Execution time: 0.04s
>>> Tests count: 2  |  Total queries count: 20  |  Total execution time: 0.08s  |  Median time one test is: 0.041s  |  Vendor: sqlite

OR

# NOTE: The with context manager does not support multi-launch number_runs > 1
# NOTE: Also you can use `async with` if you capture queries in async context.
with CaptureQueries(number_runs=1, advanced_verb=True) as ctx:
    response = self.client.get(url)

>>> Queries count: 10  |  Execution time: 0.04s  |  Vendor: sqlite

Example of output when using queries and explain:

for _ in CaptureQueries(advanced_verb=True, queries=True, explain=True):
    list(Reporter.objects.filter(pk=1))
    list(Article.objects.filter(pk=1))

>>> Test 1 | Queries count: 2 | Execution time: 0.22s
>>>
>>>
>>> [1] time=[0.109] explain=['2 0 0 SEARCH TABLE tests_reporter USING INTEGER PRIMARY KEY (rowid=?)']
>>> SELECT "tests_reporter"."id",
>>>     "tests_reporter"."full_name"
>>> FROM "tests_reporter"
>>> WHERE "tests_reporter"."id" = 1
>>>
>>>
>>> [2] time=[0.109] explain=['2 0 0 SEARCH TABLE tests_article USING INTEGER PRIMARY KEY (rowid=?)']
>>> SELECT "tests_article"."id",
>>>     "tests_article"."pub_date",
>>>     "tests_article"."headline",
>>>     "tests_article"."content",
>>>     "tests_article"."reporter_id"
>>> FROM "tests_article"
>>> WHERE "tests_article"."id" = 1
>>>
>>>
>>> Tests count: 1  |  Total queries count: 2  |  Total execution time: 0.22s  |  Median time one test is: 0.109s  |  Vendor: sqlite

Customization of the display

To customize the display of SQL queries, you can import a list with handlers and remove handlers from it or expand it with your own handlers.

from capture_db_queries import settings, IHandler

# NOTE: The handler must comply with the specified interface.
class SomeHandler(IHandler):
    def handle(self, queries_log):
        for query in queries_log:
            query.sql = "Hello World!"
        return queries_log

settings.PRINTER_HANDLERS.remove("capture_db_queries.handlers.ColorizeSqlHandler")
settings.PRINTER_HANDLERS.append("path.to.your.handler.SomeHandler")

TODO:

  1. Add support for async loop and async func decorator, call, aiter, anext
  2. Add support for other ORM's, SQLAlchemy, etc.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

capture_db_queries-1.2.8.tar.gz (31.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

capture_db_queries-1.2.8-py3-none-any.whl (19.7 kB view details)

Uploaded Python 3

File details

Details for the file capture_db_queries-1.2.8.tar.gz.

File metadata

  • Download URL: capture_db_queries-1.2.8.tar.gz
  • Upload date:
  • Size: 31.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for capture_db_queries-1.2.8.tar.gz
Algorithm Hash digest
SHA256 6e22c5f2ac54cdba1143fb3c7fbd6acb37bbee00e746262183b137a35c35d3d9
MD5 ef6efa982f4c385bef22b92a7e0a786c
BLAKE2b-256 f5146674d4c5fc157b9405375e8b8348e9a4fe05f5a98f0042723f4753cb3d35

See more details on using hashes here.

Provenance

The following attestation bundles were made for capture_db_queries-1.2.8.tar.gz:

Publisher: publish-to-pypi.yml on Friskes/capture-db-queries

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file capture_db_queries-1.2.8-py3-none-any.whl.

File metadata

File hashes

Hashes for capture_db_queries-1.2.8-py3-none-any.whl
Algorithm Hash digest
SHA256 d865b0455de543b63f674d96e7ff4b6eef7f76c5be7aadb3ccb5c6914a7a9be0
MD5 113eea2d6c173558578d11f1db4ecb3b
BLAKE2b-256 334b6241eb62e595d142538e46d1e22becbf64cf03c5c160d252c0443c35a0e2

See more details on using hashes here.

Provenance

The following attestation bundles were made for capture_db_queries-1.2.8-py3-none-any.whl:

Publisher: publish-to-pypi.yml on Friskes/capture-db-queries

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page