# Path: boardinghouse/signals.py

# 
# Path: boardinghouse/exceptions.py
# class Forbidden(Exception):
#     """
#     An exception that will be raised when an attempt to activate a non-valid
#     schema is made.
#     """
# 
# Path: boardinghouse/receivers.py
# @receiver(models.signals.post_save, sender=Schema, weak=False, dispatch_uid='create-schema')
# def create_schema(sender, instance, created, **kwargs):
#     """
#     Actually create the schema in the database.
# 
#     We do this in a signal handler instead of .save() so we can catch
#     those created using raw methods.
# 
#     How do we indicate when we should be using a different template?
#     """
#     if created:
#         schema_name = instance.schema
# 
#         # How can we work out what values need to go here?
#         # Currently, we just allow a single attribute `_clone`, that,
#         # if set, will indicate that we should clone a schema.
#         template_name = getattr(instance, '_clone', settings.TEMPLATE_SCHEMA)
#         include_records = bool(getattr(instance, '_clone', False))
# 
#         cursor = connection.cursor()
# 
#         if _schema_exists(schema_name):
#             raise ValueError('Attempt to create an existing schema: {0}'.format(schema_name))
# 
#         cursor.execute("SELECT clone_schema(%s, %s, %s)", [
#             template_name,
#             schema_name,
#             include_records
#         ])
#         cursor.close()
# 
#         if schema_name != settings.TEMPLATE_SCHEMA:
#             signals.schema_created.send(sender=get_schema_model(), schema=schema_name)
# 
#         LOGGER.info('New schema created: %s', schema_name)
# 
# @receiver(models.signals.post_delete, sender=Schema, weak=False)
# def drop_schema(sender, instance, **kwargs):
#     signals.schemata_deleted.send(sender=sender, schemata=[instance.schema])
# 
# Path: boardinghouse/schema.py
# def _table_exists(table_name, schema=None):
#     cursor = connection.cursor()
#     cursor.execute("""SELECT *
#                         FROM information_schema.tables
#                        WHERE table_name = %s
#                          AND table_schema = %s""", [table_name, schema or settings.PUBLIC_SCHEMA])
#     return bool(cursor.fetchone())
# 
# Path: boardinghouse/contrib/template/models.py
# class SchemaTemplate(SharedSchemaMixin, models.Model):
#     """
#     A ``boardinghouse.contrib.template.models.SchemaTemplate`` can be used
#     for creating a new schema complete with some initial data.
#     """
#     template_schema_id = models.AutoField(primary_key=True)
#     name = models.CharField(max_length=128, unique=True)
#     is_active = models.BooleanField(default=True)
#     description = models.TextField(null=True, blank=True)
# 
#     objects = SchemaTemplateQuerySet.as_manager()
# 
#     class Meta:
#         default_permissions = ('add', 'change', 'delete', 'view', 'activate', 'clone')
#         verbose_name = lazy(verbose_name, six.text_type)()
#         verbose_name_plural = lazy(verbose_name_plural, six.text_type)()
# 
#     def __str__(self):
#         return self.name
# 
#     @property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_TEMPLATE_PREFIX, self.pk)
# 
#     def activate(self):
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


from django.conf import settings
from django.dispatch import receiver
from django.db import models
from boardinghouse import signals
from boardinghouse.exceptions import Forbidden
from boardinghouse.receivers import create_schema, drop_schema
from boardinghouse.schema import _table_exists
from .models import SchemaTemplate



models.signals.post_save.connect(create_schema,
                                 sender=SchemaTemplate,
                                 dispatch_uid='create-schema-template')

models.signals.post_delete.connect(drop_schema, sender=SchemaTemplate)


@receiver(signals.schema_aware_operation, weak=False, dispatch_uid='execute-all-templates')
def execute_on_all_templates(sender, db_table, function, **kwargs):
    if _table_exists(SchemaTemplate._meta.db_table):
        for schema in SchemaTemplate.objects.all():
            schema.activate()
            function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))



# Path: boardinghouse/signals.py

# 
# Path: boardinghouse/exceptions.py
# class Forbidden(Exception):
#     """
#     An exception that will be raised when an attempt to activate a non-valid
#     schema is made.
#     """
# 
# Path: boardinghouse/receivers.py
# @receiver(models.signals.post_save, sender=Schema, weak=False, dispatch_uid='create-schema')
# def create_schema(sender, instance, created, **kwargs):
#     """
#     Actually create the schema in the database.
# 
#     We do this in a signal handler instead of .save() so we can catch
#     those created using raw methods.
# 
#     How do we indicate when we should be using a different template?
#     """
#     if created:
#         schema_name = instance.schema
# 
#         # How can we work out what values need to go here?
#         # Currently, we just allow a single attribute `_clone`, that,
#         # if set, will indicate that we should clone a schema.
#         template_name = getattr(instance, '_clone', settings.TEMPLATE_SCHEMA)
#         include_records = bool(getattr(instance, '_clone', False))
# 
#         cursor = connection.cursor()
# 
#         if _schema_exists(schema_name):
#             raise ValueError('Attempt to create an existing schema: {0}'.format(schema_name))
# 
#         cursor.execute("SELECT clone_schema(%s, %s, %s)", [
#             template_name,
#             schema_name,
#             include_records
#         ])
#         cursor.close()
# 
#         if schema_name != settings.TEMPLATE_SCHEMA:
#             signals.schema_created.send(sender=get_schema_model(), schema=schema_name)
# 
#         LOGGER.info('New schema created: %s', schema_name)
# 
# @receiver(models.signals.post_delete, sender=Schema, weak=False)
# def drop_schema(sender, instance, **kwargs):
#     signals.schemata_deleted.send(sender=sender, schemata=[instance.schema])
# 
# Path: boardinghouse/schema.py
# def _table_exists(table_name, schema=None):
#     cursor = connection.cursor()
#     cursor.execute("""SELECT *
#                         FROM information_schema.tables
#                        WHERE table_name = %s
#                          AND table_schema = %s""", [table_name, schema or settings.PUBLIC_SCHEMA])
#     return bool(cursor.fetchone())
# 
# Path: boardinghouse/contrib/template/models.py
# class SchemaTemplate(SharedSchemaMixin, models.Model):
#     """
#     A ``boardinghouse.contrib.template.models.SchemaTemplate`` can be used
#     for creating a new schema complete with some initial data.
#     """
#     template_schema_id = models.AutoField(primary_key=True)
#     name = models.CharField(max_length=128, unique=True)
#     is_active = models.BooleanField(default=True)
#     description = models.TextField(null=True, blank=True)
# 
#     objects = SchemaTemplateQuerySet.as_manager()
# 
#     class Meta:
#         default_permissions = ('add', 'change', 'delete', 'view', 'activate', 'clone')
#         verbose_name = lazy(verbose_name, six.text_type)()
#         verbose_name_plural = lazy(verbose_name_plural, six.text_type)()
# 
#     def __str__(self):
#         return self.name
# 
#     @property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_TEMPLATE_PREFIX, self.pk)
# 
#     def activate(self):
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


# Path: boardinghouse/contrib/template/receivers.py
from django.conf import settings
from django.dispatch import receiver
from django.db import models
from boardinghouse import signals
from boardinghouse.exceptions import Forbidden
from boardinghouse.receivers import create_schema, drop_schema
from boardinghouse.schema import _table_exists
from .models import SchemaTemplate




models.signals.post_save.connect(create_schema,
                                 sender=SchemaTemplate,
                                 dispatch_uid='create-schema-template')

models.signals.post_delete.connect(drop_schema, sender=SchemaTemplate)


@receiver(signals.schema_aware_operation, weak=False, dispatch_uid='execute-all-templates')
def execute_on_all_templates(sender, db_table, function, **kwargs):
    if _table_exists(SchemaTemplate._meta.db_table):
        for schema in SchemaTemplate.objects.all():
            schema.activate()
            function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))



@receiver(signals.session_requesting_schema_change, weak=False, dispatch_uid='change-to-schema-template')