Files
enviPy-bayer/epdb/management/commands/recreate_db.py
2026-03-06 22:11:22 +13:00

77 lines
2.1 KiB
Python

import os
import subprocess
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"-n",
"--name",
type=str,
help="Name of the database to recreate. Default is 'appdb'",
default="appdb",
)
parser.add_argument(
"-d",
"--dump",
type=str,
help="Path to the dump file",
default="./fixtures/db.dump",
)
parser.add_argument(
"-ou",
"--oldurl",
type=str,
help="Old URL, e.g. https://envipath.org/",
default="https://envipath.org/",
)
parser.add_argument(
"-nu",
"--newurl",
type=str,
help="New URL, e.g. http://localhost:8000/",
default="http://localhost:8000/",
)
def handle(self, *args, **options):
dump_file = options["dump"]
if not os.path.exists(dump_file):
raise ValueError(f"Dump file {dump_file} does not exist")
print(f"Dropping database {options['name']} y/n: ", end="")
if input() in "yY":
result = subprocess.run(
["dropdb", "appdb"],
capture_output=True,
text=True,
)
print(result.stdout)
else:
raise ValueError("Aborted")
print(f"Creating database {options['name']}")
result = subprocess.run(
["createdb", "appdb"],
capture_output=True,
text=True,
)
print(result.stdout)
print(f"Restoring database {options['name']} from {dump_file}")
result = subprocess.run(
["pg_restore", "-d", "appdb", dump_file, "--no-owner"],
capture_output=True,
text=True,
)
print(result.stdout)
call_command("localize_urls", "--old", options["oldurl"], "--new", options["newurl"])