Created
October 11, 2020 09:54
-
-
Save pirate/a52cafddea8537b8a9f2f2d970cb67bc to your computer and use it in GitHub Desktop.
Create a django settings DATABASES entry for each tenant schema in a PostgreSQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_tenant_schemas(): | |
if IS_TESTING or IS_MIGRATING: | |
return ["public", "test"] | |
DATABASE_UTIL_CONNECTION = psycopg2.connect( | |
host=POSTGRES_HOST, | |
port=POSTGRES_PORT, | |
sslmode=POSTGRES_SSL, | |
user=POSTGRES_USER, | |
password=POSTGRES_PASSWORD, | |
dbname=POSTGRES_DB, | |
) | |
cursor = DATABASE_UTIL_CONNECTION.cursor() | |
cursor.execute("select schema_name from information_schema.schemata;") | |
try: | |
return [ | |
result[0] for result in cursor.fetchall() if result[0] not in ("information_schema", "pg_catalog") | |
] | |
finally: | |
DATABASE_UTIL_CONNECTION.close() | |
def get_tenant_databases(): | |
return { | |
schema_name: { | |
"ENGINE": "django.db.backends.postgresql_psycopg2", | |
"HOST": POSTGRES_HOST, | |
"PORT": POSTGRES_PORT, | |
"USER": POSTGRES_USER, | |
"PASSWORD": POSTGRES_PASSWORD, | |
"NAME": f"test_{POSTGRES_DB}" if IS_TESTING else POSTGRES_DB, | |
"OPTIONS": { | |
#"isolation_level": psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE, | |
"sslmode": POSTGRES_SSL, | |
"options": f"-c search_path={schema_name}", | |
}, | |
} | |
for schema_name in get_tenant_schemas() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment