capture-db-queries


Namecapture-db-queries JSON
Version 1.2.5 PyPI version JSON
download
home_pagehttps://github.com/Friskes/capture-db-queries
SummaryDecorator for measuring the time and number of database queries
upload_time2024-12-01 13:12:30
maintainerNone
docs_urlNone
authorFriskes
requires_python>=3.8
licenseMIT License Copyright (c) 2024 Friskes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords django database
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Class to simplify the search for slow and suboptimal sql queries to the database in django projects.

<div align="center">

| Project   |     | Status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|-----------|:----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| CI/CD     |     | [![Latest Release](https://github.com/Friskes/capture-db-queries/actions/workflows/publish-to-pypi.yml/badge.svg)](https://github.com/Friskes/capture-db-queries/actions/workflows/publish-to-pypi.yml)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Quality   |     | [![Coverage](https://codecov.io/github/Friskes/capture-db-queries/graph/badge.svg?token=vKez4Pycrc)](https://codecov.io/github/Friskes/capture-db-queries)                                                                                                                                                                                                                                                                                                                               |
| Package   |     | [![PyPI - Version](https://img.shields.io/pypi/v/capture-db-queries?labelColor=202235&color=edb641&logo=python&logoColor=edb641)](https://badge.fury.io/py/capture-db-queries) ![PyPI - Support Python Versions](https://img.shields.io/pypi/pyversions/capture-db-queries?labelColor=202235&color=edb641&logo=python&logoColor=edb641) ![Project PyPI - Downloads](https://img.shields.io/pypi/dm/capture-db-queries?logo=python&label=downloads&labelColor=202235&color=edb641&logoColor=edb641)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Meta      |     | [![types - Mypy](https://img.shields.io/badge/types-Mypy-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://spdx.org/licenses/) [![code style - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/format.json&labelColor=202235)](https://github.com/astral-sh/ruff) |

</div>

## 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
    ```bash
    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

## Usage examples

```python
from capture_db_queries import CaptureQueries
```

```python
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

```python
@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

```python
# NOTE: The with context manager does not support multi-launch number_runs > 1
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:

```python
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.

```python
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 other ORM's, SQLAlchemy, etc.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Friskes/capture-db-queries",
    "name": "capture-db-queries",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "Django, Database",
    "author": "Friskes",
    "author_email": "Friskes <friskesx@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/dc/8d/b61e7aa08e66f5711a91d595f91668d048599a3dceb3ebd0790e9b1de830/capture_db_queries-1.2.5.tar.gz",
    "platform": null,
    "description": "# Class to simplify the search for slow and suboptimal sql queries to the database in django projects.\n\n<div align=\"center\">\n\n| Project   |     | Status                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |\n|-----------|:----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| CI/CD     |     | [![Latest Release](https://github.com/Friskes/capture-db-queries/actions/workflows/publish-to-pypi.yml/badge.svg)](https://github.com/Friskes/capture-db-queries/actions/workflows/publish-to-pypi.yml)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| Quality   |     | [![Coverage](https://codecov.io/github/Friskes/capture-db-queries/graph/badge.svg?token=vKez4Pycrc)](https://codecov.io/github/Friskes/capture-db-queries)                                                                                                                                                                                                                                                                                                                               |\n| Package   |     | [![PyPI - Version](https://img.shields.io/pypi/v/capture-db-queries?labelColor=202235&color=edb641&logo=python&logoColor=edb641)](https://badge.fury.io/py/capture-db-queries) ![PyPI - Support Python Versions](https://img.shields.io/pypi/pyversions/capture-db-queries?labelColor=202235&color=edb641&logo=python&logoColor=edb641) ![Project PyPI - Downloads](https://img.shields.io/pypi/dm/capture-db-queries?logo=python&label=downloads&labelColor=202235&color=edb641&logoColor=edb641)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |\n| Meta      |     | [![types - Mypy](https://img.shields.io/badge/types-Mypy-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-202235.svg?logo=python&labelColor=202235&color=edb641&logoColor=edb641)](https://spdx.org/licenses/) [![code style - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/format.json&labelColor=202235)](https://github.com/astral-sh/ruff) |\n\n</div>\n\n## About class\n- 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.\n\n- 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.\n\n> **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.**\n\n## Install\n1. Install package\n    ```bash\n    pip install capture-db-queries\n    ```\n\n## About class parameters\n> *All parameters are purely optional.*\n\n- Optional parameters:\n    - `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\"**.\n    - `number_runs`: The number of runs of the decorated function or test for loop.\n    - `verbose`: Displaying the final results of test measurements within all `number_runs`.\n    - `advanced_verb`: Displaying the result of each test measurement.\n    - `auto_call_func`: Autorun of the decorated function. *(without passing arguments to the function, since the launch takes place inside the class)*.\n    - `queries`: Displaying colored and formatted SQL queries to the database.\n    - `explain`: Displaying explain information about each query. (has no effect on the original query).\n    - `explain_opts`: Parameters for explain. *(for more information about the parameters for explain, see the documentation for your DBMS).*\n    - `connection`: Connecting to your database, by default: django.db.connection\n\n## Usage examples\n\n```python\nfrom capture_db_queries import CaptureQueries\n```\n\n```python\nfor ctx in CaptureQueries(number_runs=2, advanced_verb=True):\n    response = self.client.get(url)\n\n>>> Test \u21161 | Queries count: 10 | Execution time: 0.04s\n>>> Test \u21162 | Queries count: 10 | Execution time: 0.04s\n>>> Tests count: 2  |  Total queries count: 20  |  Total execution time: 0.08s  |  Median time one test is: 0.041s  |  Vendor: sqlite\n```\n\n#### OR\n\n```python\n@CaptureQueries(number_runs=2, advanced_verb=True)\ndef test_request():\n    response = self.client.get(url)\n\n>>> Test \u21161 | Queries count: 10 | Execution time: 0.04s\n>>> Test \u21162 | Queries count: 10 | Execution time: 0.04s\n>>> Tests count: 2  |  Total queries count: 20  |  Total execution time: 0.08s  |  Median time one test is: 0.041s  |  Vendor: sqlite\n```\n\n#### OR\n\n```python\n# NOTE: The with context manager does not support multi-launch number_runs > 1\nwith CaptureQueries(number_runs=1, advanced_verb=True) as ctx:\n    response = self.client.get(url)\n\n>>> Queries count: 10  |  Execution time: 0.04s  |  Vendor: sqlite\n```\n\n> ### Example of output when using queries and explain:\n\n```python\nfor _ in CaptureQueries(advanced_verb=True, queries=True, explain=True):\n    list(Reporter.objects.filter(pk=1))\n    list(Article.objects.filter(pk=1))\n\n>>> Test \u21161 | Queries count: 2 | Execution time: 0.22s\n>>>\n>>>\n>>> \u2116[1] time=[0.109] explain=['2 0 0 SEARCH TABLE tests_reporter USING INTEGER PRIMARY KEY (rowid=?)']\n>>> SELECT \"tests_reporter\".\"id\",\n>>>     \"tests_reporter\".\"full_name\"\n>>> FROM \"tests_reporter\"\n>>> WHERE \"tests_reporter\".\"id\" = 1\n>>>\n>>>\n>>> \u2116[2] time=[0.109] explain=['2 0 0 SEARCH TABLE tests_article USING INTEGER PRIMARY KEY (rowid=?)']\n>>> SELECT \"tests_article\".\"id\",\n>>>     \"tests_article\".\"pub_date\",\n>>>     \"tests_article\".\"headline\",\n>>>     \"tests_article\".\"content\",\n>>>     \"tests_article\".\"reporter_id\"\n>>> FROM \"tests_article\"\n>>> WHERE \"tests_article\".\"id\" = 1\n>>>\n>>>\n>>> Tests count: 1  |  Total queries count: 2  |  Total execution time: 0.22s  |  Median time one test is: 0.109s  |  Vendor: sqlite\n```\n\n### Customization of the display\n> 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.\n\n```python\nfrom capture_db_queries import settings, IHandler\n\n# NOTE: The handler must comply with the specified interface.\nclass SomeHandler(IHandler):\n    def handle(self, queries_log):\n        for query in queries_log:\n            query.sql = \"Hello World!\"\n        return queries_log\n\nsettings.PRINTER_HANDLERS.remove(\"capture_db_queries.handlers.ColorizeSqlHandler\")\nsettings.PRINTER_HANDLERS.append(\"path.to.your.handler.SomeHandler\")\n```\n\n## TODO:\n1. Add support for other ORM's, SQLAlchemy, etc.\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2024 Friskes  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Decorator for measuring the time and number of database queries",
    "version": "1.2.5",
    "project_urls": {
        "Changelog": "https://github.com/Friskes/capture-db-queries/releases/",
        "Homepage": "https://github.com/Friskes/capture-db-queries",
        "Issues": "https://github.com/Friskes/capture-db-queries/issues"
    },
    "split_keywords": [
        "django",
        " database"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e836c5bbc40b76afa1403e7582cebf6aec9498f75af2261443aa343b1bbde140",
                "md5": "545a3b773bfa72457073abffd010775c",
                "sha256": "1605c617fc86ac02fa711e37d7a4a85ec24051b9df560ba9bb6d1097bfa10439"
            },
            "downloads": -1,
            "filename": "capture_db_queries-1.2.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "545a3b773bfa72457073abffd010775c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 19101,
            "upload_time": "2024-12-01T13:12:14",
            "upload_time_iso_8601": "2024-12-01T13:12:14.989144Z",
            "url": "https://files.pythonhosted.org/packages/e8/36/c5bbc40b76afa1403e7582cebf6aec9498f75af2261443aa343b1bbde140/capture_db_queries-1.2.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "dc8db61e7aa08e66f5711a91d595f91668d048599a3dceb3ebd0790e9b1de830",
                "md5": "ef3211340dfda9647aca71dfe0739905",
                "sha256": "dfd0879906e009152c48df68a3d713e383ccc17bb69b7d0c0cbbba3c53d911dc"
            },
            "downloads": -1,
            "filename": "capture_db_queries-1.2.5.tar.gz",
            "has_sig": false,
            "md5_digest": "ef3211340dfda9647aca71dfe0739905",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 30935,
            "upload_time": "2024-12-01T13:12:30",
            "upload_time_iso_8601": "2024-12-01T13:12:30.020006Z",
            "url": "https://files.pythonhosted.org/packages/dc/8d/b61e7aa08e66f5711a91d595f91668d048599a3dceb3ebd0790e9b1de830/capture_db_queries-1.2.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-01 13:12:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Friskes",
    "github_project": "capture-db-queries",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "capture-db-queries"
}
        
Elapsed time: 0.41424s