Created
November 22, 2021 11:06
-
-
Save eshaan7/e2f172cc984f5a86362e34d5a77038da to your computer and use it in GitHub Desktop.
Django management command to auto-create database in postgreSQL.
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
import re | |
from django.conf import settings | |
from django.core.management.commands.migrate import Command as MigrateCommand | |
from django.db import DEFAULT_DB_ALIAS, OperationalError, connections | |
from django.db.utils import ConnectionHandler | |
class Command(MigrateCommand): | |
""" | |
overwrite `MigrateCommand` to automatically create the app-specific DB. | |
""" | |
def handle(self, *args, **options): | |
try: | |
super().handle(*args, **options) | |
except OperationalError as exception: | |
if re.search(r'FATAL: database "\S+?" does not exist', str(exception)): | |
selected_database = options["database"] | |
if self.create_db(selected_database): | |
super().handle(*args, **options) | |
else: | |
raise | |
else: | |
raise | |
def create_db(self, database): | |
database_vendor = connections[database].vendor | |
if database_vendor == "postgresql": | |
database_config = settings.DATABASES[database] | |
handler = ConnectionHandler() | |
database_name = database_config["NAME"] | |
with handler[DEFAULT_DB_ALIAS].cursor() as cursor: | |
cursor.execute('CREATE DATABASE "{}"'.format(database_name)) | |
self.stdout.write("Auto-created database '{}'".format(database_name)) | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment