Source code for ferrosoft.apps.ferrobase.management.commands.listtenants

from django.core.management import BaseCommand
from django.db import connection
from tabulate import tabulate

from ferrosoft.apps.ferrobase.models import Tenant


[docs] class Command(BaseCommand): """Management command that lists tenants with their database sizes. Outputs a tabulated view of tenant ID, name, active status, and the pretty-printed PostgreSQL database size. Pass ``--all`` to include inactive tenants. """
[docs] def add_arguments(self, parser): parser.add_argument( "--all", action="store_true", help="List tenants including inactive ones", default=False, )
[docs] def handle(self, *args, **options): with connection.cursor() as cursor: if not options["all"]: tenants = Tenant.objects.filter(active=True).order_by("name") else: tenants = Tenant.objects.order_by("name") if len(tenants) == 0: self.stderr.write( self.style.WARNING( "No tenants found. Create one using addtenant command." ) ) return tenant_display = [] for tenant in tenants: try: cursor.execute( "SELECT pg_size_pretty(pg_database_size('%s'))" % tenant.database_name ) result = cursor.fetchone() size = result[0] except: size = "0 kB" tenant_display.append( ( str(tenant.pk), tenant.name, "*" if tenant.active else "", size, ) ) print( tabulate( tenant_display, headers=[ "ID", "Name", "Active", "Database Size", ], ) )