# Path: psqlextra/manager/manager.py
# class PostgresManager(Manager.from_queryset(PostgresQuerySet)):
#     """Adds support for PostgreSQL specifics."""
# 
#     use_in_migrations = True
# 
#     def __init__(self, *args, **kwargs):
#         """Initializes a new instance of :see:PostgresManager."""
# 
#         super().__init__(*args, **kwargs)
# 
#         # make sure our back-end is set in at least one db and refuse to proceed
#         has_psqlextra_backend = any(
#             [
#                 db_settings
#                 for db_settings in settings.DATABASES.values()
#                 if "psqlextra" in db_settings["ENGINE"]
#             ]
#         )
# 
#         if not has_psqlextra_backend:
#             raise ImproperlyConfigured(
#                 (
#                     "Could not locate the 'psqlextra.backend'. "
#                     "django-postgres-extra cannot function without "
#                     "the 'psqlextra.backend'. Set DATABASES.ENGINE."
#                 )
#             )
# 
#     def truncate(
#         self, cascade: bool = False, using: Optional[str] = None
#     ) -> None:
#         """Truncates this model/table using the TRUNCATE statement.
# 
#         This DELETES ALL ROWS. No signals will be fired.
# 
#         See: https://www.postgresql.org/docs/9.1/sql-truncate.html
# 
#         Arguments:
#             cascade:
#                 Whether to delete dependent rows. If set to
#                 False, an error will be raised if there
#                 are rows in other tables referencing
#                 the rows you're trying to delete.
#         """
# 
#         connection = connections[using or "default"]
#         table_name = connection.ops.quote_name(self.model._meta.db_table)
# 
#         with connection.cursor() as cursor:
#             sql = "TRUNCATE TABLE %s" % table_name
#             if cascade:
#                 sql += " CASCADE"
# 
#             cursor.execute(sql)
# 
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
#     """Base class for for taking advantage of PostgreSQL specific features."""
# 
#     class Meta:
#         abstract = True
#         base_manager_name = "objects"
# 
#     objects = PostgresManager()
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model


import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import override_settings
from psqlextra.manager import PostgresManager
from psqlextra.models import PostgresModel
from .fake_model import get_fake_model
def test_manager_backend_not_set():
    """Tests whether creating a new instance of
    :see:PostgresManager fails if no database
    has `psqlextra.backend` configured
    as its ENGINE."""

    with override_settings(
        DATABASES={"default": {"ENGINE": "django.db.backends.postgresql"}}
    ):
        with pytest.raises(ImproperlyConfigured):
            PostgresManager()


def test_manager_truncate():
    """Tests whether truncating a table works."""

    model = get_fake_model({"name": models.CharField(max_length=255)})

    model.objects.create(name="henk1")
    model.objects.create(name="henk2")

    assert model.objects.count() == 2
    model.objects.truncate()
    assert model.objects.count() == 0


@pytest.mark.django_db(transaction=True)
def test_manager_truncate_cascade():
    """Tests whether truncating a table with cascade works."""


# Path: psqlextra/manager/manager.py
# class PostgresManager(Manager.from_queryset(PostgresQuerySet)):
#     """Adds support for PostgreSQL specifics."""
# 
#     use_in_migrations = True
# 
#     def __init__(self, *args, **kwargs):
#         """Initializes a new instance of :see:PostgresManager."""
# 
#         super().__init__(*args, **kwargs)
# 
#         # make sure our back-end is set in at least one db and refuse to proceed
#         has_psqlextra_backend = any(
#             [
#                 db_settings
#                 for db_settings in settings.DATABASES.values()
#                 if "psqlextra" in db_settings["ENGINE"]
#             ]
#         )
# 
#         if not has_psqlextra_backend:
#             raise ImproperlyConfigured(
#                 (
#                     "Could not locate the 'psqlextra.backend'. "
#                     "django-postgres-extra cannot function without "
#                     "the 'psqlextra.backend'. Set DATABASES.ENGINE."
#                 )
#             )
# 
#     def truncate(
#         self, cascade: bool = False, using: Optional[str] = None
#     ) -> None:
#         """Truncates this model/table using the TRUNCATE statement.
# 
#         This DELETES ALL ROWS. No signals will be fired.
# 
#         See: https://www.postgresql.org/docs/9.1/sql-truncate.html
# 
#         Arguments:
#             cascade:
#                 Whether to delete dependent rows. If set to
#                 False, an error will be raised if there
#                 are rows in other tables referencing
#                 the rows you're trying to delete.
#         """
# 
#         connection = connections[using or "default"]
#         table_name = connection.ops.quote_name(self.model._meta.db_table)
# 
#         with connection.cursor() as cursor:
#             sql = "TRUNCATE TABLE %s" % table_name
#             if cascade:
#                 sql += " CASCADE"
# 
#             cursor.execute(sql)
# 
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
#     """Base class for for taking advantage of PostgreSQL specific features."""
# 
#     class Meta:
#         abstract = True
#         base_manager_name = "objects"
# 
#     objects = PostgresManager()
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model


# Path: tests/test_manager.py
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import override_settings
from psqlextra.manager import PostgresManager
from psqlextra.models import PostgresModel
from .fake_model import get_fake_model

def test_manager_backend_not_set():
    """Tests whether creating a new instance of
    :see:PostgresManager fails if no database
    has `psqlextra.backend` configured
    as its ENGINE."""

    with override_settings(
        DATABASES={"default": {"ENGINE": "django.db.backends.postgresql"}}
    ):
        with pytest.raises(ImproperlyConfigured):
            PostgresManager()


def test_manager_truncate():
    """Tests whether truncating a table works."""

    model = get_fake_model({"name": models.CharField(max_length=255)})

    model.objects.create(name="henk1")
    model.objects.create(name="henk2")

    assert model.objects.count() == 2
    model.objects.truncate()
    assert model.objects.count() == 0


@pytest.mark.django_db(transaction=True)
def test_manager_truncate_cascade():
    """Tests whether truncating a table with cascade works."""


    model_1 = get_fake_model({"name": models.CharField(max_length=255)})