Source code for ferrosoft.apps.ferrobase.management.commands.deltenant
from django.core.management import BaseCommand
from django.db import connection
from ferrosoft.apps.ferrobase.models import Tenant
[docs]
class Command(BaseCommand):
"""Management command that removes one or more tenants from the platform.
Without ``--force``, only the tenant record is deleted and the SQL
commands to drop the database and role are printed for manual review.
With ``--force``, the database and PostgreSQL role are also dropped
immediately.
"""
help = "Delete tenants from Ferrosoft Platform"
[docs]
def add_arguments(self, parser):
parser.add_argument("name", nargs="+", type=str)
parser.add_argument(
"--force",
action="store_true",
help="Delete database and role in addition to tenant record",
)
[docs]
def handle(self, *args, **options):
with connection.cursor() as cursor:
for name in options["name"]:
tenant = Tenant.objects.filter(name=name).first()
if not tenant:
self.stderr.write(self.style.ERROR("Tenant not found: %s" % name))
return
tenant_db_name = tenant.database_name
drop_db_command = "DROP DATABASE %s" % tenant_db_name
drop_role_command = "DROP ROLE %s" % tenant_db_name
tenant.delete()
self.stderr.write(
self.style.SUCCESS("Deleted tenant from tenant table.")
)
if options["force"]:
try:
cursor.execute(drop_db_command)
cursor.execute(drop_role_command)
self.stderr.write(
self.style.SUCCESS("Deleted database and role.")
)
except Exception as e:
self.stderr.write(
"Failed deleting database or role: %s" % e,
)
else:
self.stderr.write(
self.style.WARNING(
"Tenant database and role have been left intact. To remove them, issue the following commands:"
)
)
self.stdout.write(drop_db_command + ";")
self.stdout.write(drop_role_command + ";")