summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenjamin Dauvergne <bdauvergne@entrouvert.com>2018-03-13 15:35:46 (GMT)
committerBenjamin Dauvergne <bdauvergne@entrouvert.com>2018-03-13 15:57:50 (GMT)
commit72ca424f10bcb2dc9da82481a71b0360f92ce3b0 (patch)
tree3ee8c05df32ed0e66637666f46da099256a6c7e6
parentb75755ffe8a9f530180c8d73eee42c83d343682a (diff)
downloadhobo-72ca424f10bcb2dc9da82481a71b0360f92ce3b0.zip
hobo-72ca424f10bcb2dc9da82481a71b0360f92ce3b0.tar.gz
hobo-72ca424f10bcb2dc9da82481a71b0360f92ce3b0.tar.bz2
multitenant: shorten schema names to stay within postgresql limits (#22494)
-rw-r--r--hobo/multitenant/middleware.py8
-rw-r--r--tests_multitenant/test_middleware.py15
2 files changed, 22 insertions, 1 deletions
diff --git a/hobo/multitenant/middleware.py b/hobo/multitenant/middleware.py
index 903d9c0..a855545 100644
--- a/hobo/multitenant/middleware.py
+++ b/hobo/multitenant/middleware.py
@@ -1,6 +1,8 @@
import os
import glob
+import hashlib
+from django.utils.encoding import smart_bytes
from django.conf import settings
from django.db import connection
from django.http import Http404, HttpResponseRedirect
@@ -27,7 +29,11 @@ class TenantMiddleware(object):
'''Convert hostname to PostgreSQL schema name'''
if hostname in getattr(settings, 'TENANT_MAPPING', {}):
return settings.TENANT_MAPPING[hostname]
- return hostname.replace('.', '_').replace('-', '_')
+ schema = hostname.replace('.', '_').replace('-', '_')
+ if len(schema) > 63:
+ digest = hashlib.md5(smart_bytes(schema)).hexdigest()[:4]
+ schema = '%s_%s_%s' % (schema[:29], digest, schema[-28:])
+ return schema
@classmethod
def get_tenant_by_hostname(cls, hostname):
diff --git a/tests_multitenant/test_middleware.py b/tests_multitenant/test_middleware.py
new file mode 100644
index 0000000..eabbbaa
--- /dev/null
+++ b/tests_multitenant/test_middleware.py
@@ -0,0 +1,15 @@
+from hobo.multitenant.middleware import TenantMiddleware
+
+
+def test_hostname2schema():
+ assert TenantMiddleware.hostname2schema('x' * 63) == ('x' * 63)
+ shortened = TenantMiddleware.hostname2schema('x' * 64)
+ # no more than 63 characters
+ assert len(shortened) == 63
+ # it's different than just the 63 first characters
+ assert shortened != ('x' * 63)
+ # but it matches the prefix
+ assert shortened[:20] == ('x' * 20)
+ # and it matches the suffix
+ assert shortened[-20:] == ('x' * 20)
+