Metadata-Version: 2.1
Name: django_integrity
Version: 0.1.0
License: BSD 3-Clause License
        
        Copyright (c) 2024, Kraken Technologies Limited
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its
           contributors may be used to endorse or promote products derived from
           this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        
Project-URL: repository, https://github.com/octoenergy/django-integrity
Project-URL: changelog, https://github.com/octoenergy/django-integrity/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: dj-database-url; extra == "dev"
Requires-Dist: django-stubs; extra == "dev"
Requires-Dist: environs; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-django; extra == "dev"
Requires-Dist: tox; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: mypy-json-report; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: rich; extra == "dev"
Requires-Dist: tomli>=1.1.0; python_version < "3.11" and extra == "dev"
Requires-Dist: typer; extra == "dev"

# Django Integrity

Django Integrity contains tools for controlling deferred constraints
and handling `IntegrityError`s in Django projects which use PostgreSQL.

## Deferrable constraints

Some PostgreSQL constraints can be defined as `DEFERRABLE`.
A constraint that is not deferred will be checked immediately after every command.
A deferred constraint check will be postponed until the end of the transaction.
A deferrable constraint will default to either `DEFERRED` or `IMMEDIATE`.

The utilities in `django_integrity.constraints` can
ensure a deferred constraint is checked immediately,
or defer an immediate constraint.

These alter the state of constraints until the end of the current transaction:

- `set_all_immediate(using=...)`
- `set_immedate(names=(...), using=...)`
- `set_deferred(names=(...), using=...)`

To enforce a constraint immediately within some limited part of a transaction,
use the `immediate(names=(...), using=...)` context manager.

### Why do we need this?

This is most likely to be useful when you want to catch a foreign-key violation
(i.e.: you have inserted a row which references different row which doesn't exist).

Django's foreign key constraints are deferred by default,
so they would normally raise an error only at the end of a transaction.
Using `try` to catch an `IntegrityError` from a foreign-key violation wouldn't work,
and you'd need to wrap the `COMMIT` instead, which is trickier.

By making the constraint `IMMEDIATE`,
the constraint would be checked on `INSERT`,
and it would be much easier to catch.

More generally,
if you have a custom deferrable constraint,
it may be useful to change the default behaviour with these tools.

## Refining `IntegrityError`

The `refine_integrity_error` context manager in `django_integrity.conversion`
will convert an `IntegrityError` into a more specific exception
based on a mapping of rules to your custom exceptions,
and will raise the `IntegrityError` if it doesn't match.

### Why do we need this?

When a database constraint is violated,
we usually expect to see an `IntegrityError`.

Sometimes we need more information about the error:
was it a unique constraint violation, or a check-constraint, or a not-null constraint?
Perhaps we ran out of 32-bit integers for our ID column?
Failing to be specific on these points could lead to bugs
where we catch an exception without realising it was not the one we expected.

### Example

```python
from django_integrity import conversion
from users.models import User


class UserAlreadyExists(Exception): ...
class EmailCannotBeNull(Exception): ...
class EmailMustBeLowerCase(Exception): ...


def create_user(email: str) -> User:
    """
    Creates a user with the provided email address.

    Raises:
        UserAlreadyExists: If the email was not unique.
        EmailCannotBeNull: If the email was None.
        EmailMustBeLowerCase: If the email had a non-lowercase character.
    """
    rules = {
        conversion.Unique(model=User, fields=("email",)): UserAlreadyExists,
        conversion.NotNull(model=User, field="email"): EmailCannotBeNull,
        conversion.Named(name="constraint_islowercase"): EmailMustBeLowerCase,
    }
    with conversion.refine_integrity_error(rules):
        User.objects.create(email=email)
```

## Supported dependencies

This package is tested against:

- Python 3.10, 3.11, or 3.12.
- Django 4.1, 4.2, or 5.0.
- PostgreSQL 12 to 16.
- psycopg2 and psycopg3.
