from contextlib import contextmanager
from threading import local

_current_tenant = local()
_MAIN = 'main'


class _DBTable(object):
    def __get__(self, obj, objtype):
        orig = getattr(obj, '_db_table', '')
        if orig:
            # TODO exempt some tables so they're shared (will screw up migrate...)
            return '%s%s' % (_current_tenant.table_prefix, orig)
        else:
            return ''

    def __set__(self, obj, value):
        if value:
            obj._db_table = value.replace(_current_tenant.table_prefix, '')
        
        
def _patch_table_names():
    import sys
    _meta = sys.modules['django.db.models.options'].Options
    _meta.db_table = _DBTable()

            
def _set_for_request(request):
    host = request.get_host()
    with _tenant(_MAIN):
        # **Must** have this import here, not at the top of the file
        from django.contrib.sites.models import Site
        Site.objects.clear_cache()
        domain = Site.objects.get_current().domain
    if not host.startswith(domain):
        tenant = host.split('.')[0]
        with _tenant(_MAIN):
            from . import models  # fix circ. import
            if not models.Tenant.objects.filter(slug=tenant).exists():
                raise ValueError
    else:
        tenant = _MAIN
    return _set(tenant)


def _set_for_tenant(tenant):
    _set(tenant)


def _table_prefix(tenant):
    return '__%s__' % tenant


def _set_default():
    _set(_MAIN)

    
def _set(tenant_id):
    _current_tenant.table_prefix = _table_prefix(tenant_id)


def _unset():
    del _current_tenant.table_prefix


def _is_main():
    return _current_tenant.table_prefix == _table_prefix(_MAIN)


@contextmanager
def _tenant(tenant_id):
    _set_for_tenant(tenant_id)
    yield
    _unset()

@@ -1,12 +1,27 @@
+import logging%0A
 from context
@@ -75,16 +75,51 @@
  local%0A%0A
+log = logging.getLogger(__name__)%0A%0A
 _current
@@ -816,16 +816,59 @@
 _host()%0A
+    log.debug('Request host is %25s' %25 host)%0A
     with
@@ -1092,16 +1092,66 @@
 .domain%0A
+        log.debug('Parent domain is %25s' %25 domain)%0A
     if n
@@ -1214,16 +1214,59 @@
 '.')%5B0%5D%0A
+        log.debug('Tenant is %25s' %25 tenant)%0A
         
@@ -1406,24 +1406,82 @@
 ).exists():%0A
+                log.error('Tenant %25s not found' %25 tenant)%0A
             
@@ -1503,32 +1503,69 @@
 Error%0A    else:%0A
+        log.debug('No tenant found')%0A
         tenant =
@@ -1826,16 +1826,62 @@
 ant_id)%0A
+    log.debug('Set tenant to %25s' %25 tenant_id)%0A
 %0A%0Adef _u
@@ -1925,16 +1925,46 @@
 _prefix%0A
+    log.debug('Unset tenant')%0A
 %0A%0Adef _i

Add logging to tenant app