Skip to content

Commit

Permalink
Refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
yubarajshrestha committed Jul 17, 2022
1 parent c18b955 commit 7619a1a
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 45 deletions.
2 changes: 1 addition & 1 deletion src/multitenancy/commands/TenancyMigrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def migration(self, tenant):

migration = Migration(
command_class=self,
connection='default',
connection="default",
migration_directory=self.option("directory"),
config_path=None,
schema=None,
Expand Down
2 changes: 1 addition & 1 deletion src/multitenancy/commands/TenancyMigrateRefresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def migration(self, tenant):

return Migration(
command_class=self,
connection='default',
connection="default",
migration_directory=self.option("directory"),
config_path=None,
schema=None,
Expand Down
2 changes: 1 addition & 1 deletion src/multitenancy/commands/TenancyMigrateReset.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def migration(self, tenant):

return Migration(
command_class=self,
connection='default',
connection="default",
migration_directory=self.option("directory"),
config_path=None,
schema=None,
Expand Down
2 changes: 1 addition & 1 deletion src/multitenancy/commands/TenancyMigrateRollback.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def migration(self, tenant):

return Migration(
command_class=self,
connection='default',
connection="default",
migration_directory=self.option("directory"),
config_path=None,
schema=None,
Expand Down
2 changes: 1 addition & 1 deletion src/multitenancy/commands/TenancyMigrateStatus.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def migration(self, tenant):

migration = Migration(
command_class=self,
connection='default',
connection="default",
migration_directory=self.option("directory"),
config_path=None,
schema=None,
Expand Down
58 changes: 35 additions & 23 deletions src/multitenancy/contexts/TenantContext.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
# flake8: noqa F501
from typing import Optional
from ..facades import Tenancy
from ..models.Tenant import Tenant
import subprocess
from masonite.environment import env

class TenantContext(object):

class TenantContext(object):
def __init__(self, tenant: Optional[Tenant] = None):
if not tenant:
raise Exception("Tenant is required")

if not isinstance(tenant, Tenant):
raise Exception("`tenant` must be an instance of Tenant")

self.tenant = tenant
self.migration_dir = env('DB_MIGRATIONS_DIR', 'databases/migrations')
self.seeders_dir = env('DB_SEEDERS_DIR', 'databases/seeds')

self.migration_dir = env("DB_MIGRATIONS_DIR", "databases/migrations")
self.seeders_dir = env("DB_SEEDERS_DIR", "databases/seeds")

def __enter__(self):
Tenancy.set_connection(self.tenant)
Expand All @@ -30,9 +31,11 @@ def migrate(self):

command = f"python craft tenancy:migrate --tenants={self.tenant.database} --d={self.migration_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)
process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output
Expand All @@ -41,10 +44,12 @@ def migrate_refresh(self):
# refreshes database of a tenant

command = f"python craft tenancy:migrate:refresh --tenants={self.tenant.database} --d={self.migration_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)

process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output
Expand All @@ -53,10 +58,12 @@ def migrate_rollback(self):
# rolls back migration changes in database of a tenant

command = f"python craft tenancy:migrate:rollback --tenants={self.tenant.database} --d={self.migration_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)

process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output
Expand All @@ -65,10 +72,12 @@ def migrate_reset(self):
# Resets the database of a tenant

command = f"python craft tenancy:migrate:reset --tenants={self.tenant.database} --d={self.migration_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)

process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output
Expand All @@ -77,10 +86,12 @@ def migrate_status(self):
# displays migration status of a tenant

command = f"python craft tenancy:migrate:status --tenants={self.tenant.database} --d={self.migration_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)

process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output
Expand All @@ -89,11 +100,12 @@ def seed(self):
# seeds data into database of a tenant

command = f"python craft tenancy:seed:run --tenants={self.tenant.database} --d={self.seeders_dir}"

process = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True, universal_newlines=True)

process = subprocess.Popen(
[command], stdout=subprocess.PIPE, shell=True, universal_newlines=True
)
output, error = process.communicate()

if error:
print(error)
return output

3 changes: 2 additions & 1 deletion src/multitenancy/contexts/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .TenantContext import TenantContext
# flake8: noqa F401
from .TenantContext import TenantContext
3 changes: 2 additions & 1 deletion src/multitenancy/facades/Tenancy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from masonite.facades import Facade


class Tenancy(metaclass=Facade):
key = "multitenancy"
key = "multitenancy"
12 changes: 1 addition & 11 deletions src/multitenancy/facades/Tenancy.pyi
Original file line number Diff line number Diff line change
@@ -1,41 +1,31 @@
from masonite.request.request import Request
from ..models.Tenant import Tenant


class Tenancy:

def reset_connection() -> None:
"""Resets the connection to the default connection."""
...

def set_connection(tenant: Tenant) -> None:
"""Sets the connection for the tenant."""
...

def get_tenants() -> list[Tenant]:
"""Returns a list of all tenants."""
...

def find_tenant(request: Request) -> Tenant | None:
"""Returns the tenant for the current request."""
...

def delete(tenant: Tenant) -> None:
"""Deletes a tenant."""
...

def create(name: str, domain: str, database: str) -> Tenant:
"""Creates a new tenant."""
...

def get_tenant_by_domain(domain: str) -> Tenant | None:
"""Returns a tenant by domain."""
...

def get_tenant_by_database(database: str) -> Tenant | None:
"""Returns a tenant by database."""
...

def get_tenant_by_id(id: int) -> Tenant | None:
"""Returns a tenant by id."""
...
...
3 changes: 2 additions & 1 deletion src/multitenancy/facades/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .Tenancy import Tenancy
# flake8: noqa F401
from .Tenancy import Tenancy
1 change: 1 addition & 0 deletions src/multitenancy/middlewares/tenant_finder_middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from masonite.middleware import Middleware
from ..facades import Tenancy


class TenantFinderMiddleware(Middleware):
"""Middleware to find the tenant for the current request."""

Expand Down
8 changes: 5 additions & 3 deletions src/multitenancy/multitenancy.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,17 @@ def find_tenant(self, request: Request) -> Tenant:
try:
self.reset_connection()
return Tenant.where_raw("database in {database}".format(database=subdomains)).first()
except Exception as e:
except Exception:
return None

def create(self, name: str, database: str, domain: str):
"""Creates a new tenant."""

tenant = Tenant.where("domain", domain).or_where("database", database).first()
if tenant:
raise Exception(f"Tenant: Domain: `{domain}` or Database: `{database}` already exists!")
raise Exception(
f"Tenant: Domain: `{domain}` or Database: `{database}` already exists!"
)

tenant = Tenant.create(name=name, domain=domain, database=database)
return tenant
Expand All @@ -114,4 +116,4 @@ def get_tenant_by_database(self, database: str):
def get_tenant_by_id(self, id: int):
"""Returns a tenant by id."""

return Tenant.find(id)
return Tenant.find(id)

0 comments on commit 7619a1a

Please sign in to comment.