# 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/signals.py

# 
# 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/contrib/demo/models.py
# class DemoSchema(SharedSchemaMixin, models.Model):
#     """A User's demo setup.
# 
#     Each user may only have at most one DemoSchema object, which will have an
#     expiry date.
# 
#     We retain a reference to the template from which it was cloned, so we can
#     easily reset it.
#     """
#     user = models.OneToOneField(settings.AUTH_USER_MODEL,
#                                 on_delete=models.CASCADE,
#                                 primary_key=True,
#                                 related_name='demo_schema')
#     expires_at = models.DateTimeField()
#     from_template = models.ForeignKey('template.SchemaTemplate',
#                                       on_delete=models.CASCADE,
#                                       related_name='demo_schemata',
#                                       limit_choices_to=~models.Q(use_for_demo=None))
# 
#     objects = ExpiringObjectsQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = 'user demo'
#         verbose_name_plural = 'user demos'
# 
#     def __str__(self):
#         if self.expired:
#             return u'Expired demo for {0} (expired {1} ago)'.format(self.user, timesince(self.expires_at))
# 
#         return u'Demo for {0}: expires at {1} ({2} from now)'.format(
#             self.user, self.expires_at, timeuntil(self.expires_at))
# 
#     @cached_property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_DEMO_PREFIX, self.user_id)
# 
#     @property
#     def expired(self):
#         return self.expires_at < timezone.now().replace(tzinfo=pytz.utc)
# 
#     @property
#     def name(self):
#         return _('Demo schema ({template_name})').format(template_name=self.from_template.name)
# 
#     @property
#     def _clone(self):
#         return self.from_template.schema
# 
#     def save(self, *args, **kwargs):
#         if not self.expires_at:
#             self.expires_at = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) + settings.BOARDINGHOUSE_DEMO_PERIOD
#         return super(DemoSchema, self).save(*args, **kwargs)
# 
#     def activate(self):
#         if self.expired:
#             raise DemoSchemaExpired()
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


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



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

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



# 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/signals.py

# 
# 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/contrib/demo/models.py
# class DemoSchema(SharedSchemaMixin, models.Model):
#     """A User's demo setup.
# 
#     Each user may only have at most one DemoSchema object, which will have an
#     expiry date.
# 
#     We retain a reference to the template from which it was cloned, so we can
#     easily reset it.
#     """
#     user = models.OneToOneField(settings.AUTH_USER_MODEL,
#                                 on_delete=models.CASCADE,
#                                 primary_key=True,
#                                 related_name='demo_schema')
#     expires_at = models.DateTimeField()
#     from_template = models.ForeignKey('template.SchemaTemplate',
#                                       on_delete=models.CASCADE,
#                                       related_name='demo_schemata',
#                                       limit_choices_to=~models.Q(use_for_demo=None))
# 
#     objects = ExpiringObjectsQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = 'user demo'
#         verbose_name_plural = 'user demos'
# 
#     def __str__(self):
#         if self.expired:
#             return u'Expired demo for {0} (expired {1} ago)'.format(self.user, timesince(self.expires_at))
# 
#         return u'Demo for {0}: expires at {1} ({2} from now)'.format(
#             self.user, self.expires_at, timeuntil(self.expires_at))
# 
#     @cached_property
#     def schema(self):
#         return '{0}{1}'.format(settings.BOARDINGHOUSE_DEMO_PREFIX, self.user_id)
# 
#     @property
#     def expired(self):
#         return self.expires_at < timezone.now().replace(tzinfo=pytz.utc)
# 
#     @property
#     def name(self):
#         return _('Demo schema ({template_name})').format(template_name=self.from_template.name)
# 
#     @property
#     def _clone(self):
#         return self.from_template.schema
# 
#     def save(self, *args, **kwargs):
#         if not self.expires_at:
#             self.expires_at = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) + settings.BOARDINGHOUSE_DEMO_PERIOD
#         return super(DemoSchema, self).save(*args, **kwargs)
# 
#     def activate(self):
#         if self.expired:
#             raise DemoSchemaExpired()
#         activate_schema(self.schema)
# 
#     def deactivate(self):
#         deactivate_schema()


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




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

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



@receiver(signals.schema_aware_operation, weak=False, dispatch_uid='execute-all-demo-schemata')