Debian Codegraph @

django_pgschemas/management/commands/cloneschema.py

raw
1 from typing import Any
2
3 from django.core.checks import Tags, run_checks
4 from django.core.management.base import BaseCommand, CommandError, CommandParser
5 from django.db.models import Model
6
7 from django_pgschemas.utils import clone_schema, get_domain_model, get_tenant_model
8
9
10 def strtobool(val: str) -> int:
11 val = val.lower()
12 if val in ("y", "yes", "t", "true", "on", "1"):
13 return 1
14 elif val in ("n", "no", "f", "false", "off", "0"):
15 return 0
16 else:
17 raise ValueError(f"invalid truth value {val!r}")
18
19
20 class Command(BaseCommand):
21 help = "Clones a schema"
22
23 def _run_checks(self, **kwargs: Any) -> list[Any]: # pragma: no cover
24 issues = run_checks(tags=[Tags.database])
25 issues.extend(super()._run_checks(**kwargs))
26 return issues
27
28 def add_arguments(self, parser: CommandParser) -> None:
29 super().add_arguments(parser)
30 parser.add_argument(
31 "source",
32 help="The name of the schema you want to clone",
33 )
34 parser.add_argument(
35 "destination",
36 help="The name of the schema you want to create as clone",
37 )
38 parser.add_argument(
39 "--noinput",
40 "--no-input",
41 action="store_false",
42 dest="interactive",
43 help="Tells Django to NOT prompt the user for input of any kind.",
44 )
45 parser.add_argument(
46 "--dry-run",
47 dest="dry_run",
48 action="store_true",
49 help="Just show what clone would do; without actually cloning.",
50 )
51
52 def _ask(self, question: str) -> int:
53 answer = None
54 while answer is None:
55 try:
56 raw_answer = input(f"{question.strip()} [Y/n] ").strip() or "y"
57 answer = strtobool(raw_answer)
58 except ValueError:
59 self.stderr.write(f"{raw_answer} is not a valid answer.")
60 pass
61 return answer
62
63 def _check_required_field(self, field: Any, exclude: list[str] | None = None) -> bool:
64 if exclude is None:
65 exclude = []
66 return (
67 field.editable
68 and not field.primary_key
69 and not field.is_relation
70 and not (
71 field.null
72 or field.has_default()
73 or (field.blank and field.empty_strings_allowed)
74 or getattr(field, "auto_now", False)
75 or getattr(field, "auto_now_add", False)
76 )
77 and field.name not in exclude
78 )
79
80 def _get_constructed_instance(self, model_class: type[Model], data: dict[str, Any]) -> Model:
81 fields = [
82 field
83 for field in model_class._meta.fields
84 if self._check_required_field(field, list(data.keys()))
85 ]
86 instance = model_class(**data)
87 if fields:
88 self.stdout.write(
89 self.style.WARNING(f"We need some data for model '{model_class._meta.model_name}':")
90 )
91 for field in fields:
92 while field.name not in data:
93 raw_value = input(f"Value for field '{field.name}': ")
94 try:
95 data[field.name] = field.clean(raw_value, None)
96 instance = model_class(**data)
97 instance.clean()
98 except Exception as e:
99 if hasattr(e, "message"):
100 self.stderr.write(e.message) # noqa
101 elif hasattr(e, "messages"):
102 self.stderr.write(" ".join(e.messages)) # noqa
103 else:
104 self.stderr.write(e)
105 data.pop(field.name, None)
106 return instance
107
108 def get_dynamic_tenant(self, **options: Any) -> tuple[Model | None, Model | None]:
109 tenant = None
110 domain = None
111 if self._ask(
112 "You are cloning a schema for a dynamic tenant. Would you like to create a database entry for it?"
113 ):
114 TenantModel = get_tenant_model()
115 DomainModel = get_domain_model()
116 if TenantModel is not None:
117 tenant = self._get_constructed_instance(
118 TenantModel, {"schema_name": options["destination"]}
119 )
120 if DomainModel is not None:
121 domain = self._get_constructed_instance(DomainModel, {"is_primary": True})
122 if options["verbosity"] >= 1:
123 self.stdout.write(self.style.WARNING("Looks good! Let's get to it!"))
124 return tenant, domain
125
126 def handle(self, *args: Any, **options: Any) -> None:
127 tenant = None
128 domain = None
129 dry_run = options.get("dry_run")
130 if options.get("interactive", True):
131 TenantModel = get_tenant_model()
132 if (
133 TenantModel is not None
134 and TenantModel.objects.filter(schema_name=options["source"]).exists()
135 ):
136 tenant, domain = self.get_dynamic_tenant(**options)
137 try:
138 clone_schema(options["source"], options["destination"], dry_run)
139 if tenant and domain:
140 if options["verbosity"] >= 1:
141 self.stdout.write("Schema cloned.")
142 if not dry_run:
143 tenant.save()
144 domain.tenant = tenant
145 if not dry_run:
146 domain.save()
147 if options["verbosity"] >= 1:
148 self.stdout.write("Tenant and domain successfully saved.")
149 if options["verbosity"] >= 1:
150 self.stdout.write("All done!")
151 except Exception as e:
152 if hasattr(e, "message"):
153 raise CommandError(e.message) # noqa
154 elif hasattr(e, "messages"):
155 raise CommandError(" ".join(e.messages)) # noqa
156 else:
157 raise CommandError(e)