66 lines
2.4 KiB
Python
66 lines
2.4 KiB
Python
from io import TextIOWrapper
|
||
from pathlib import Path
|
||
|
||
from django.conf import settings
|
||
from django.core.management.base import BaseCommand, CommandError
|
||
from django.db import connection, transaction
|
||
from django.db.utils import ProgrammingError
|
||
|
||
from address.models import AddressObject, House
|
||
from address.sql_dump import (
|
||
apply_pg_dump,
|
||
drop_foreign_keys,
|
||
listed_foreign_keys,
|
||
open_sql_dump,
|
||
restore_foreign_keys,
|
||
)
|
||
|
||
|
||
class Command(BaseCommand):
|
||
help = "Загрузить data-only дамп PostgreSQL из ZIP, если AddressObject пуст"
|
||
|
||
def add_arguments(self, parser):
|
||
parser.add_argument(
|
||
"file",
|
||
nargs="?",
|
||
type=Path,
|
||
default=None,
|
||
help="Путь к data.sql.zip (по умолчанию data.sql.zip в корне проекта)",
|
||
)
|
||
|
||
def handle(self, *args, **options):
|
||
path = options["file"] or Path(settings.BASE_DIR) / "data.sql.zip"
|
||
if not path.is_file():
|
||
self.stdout.write(f"Пропуск импорта SQL: нет файла {path}")
|
||
return
|
||
|
||
try:
|
||
if AddressObject.objects.exists():
|
||
self.stdout.write("Пропуск импорта SQL: в AddressObject уже есть записи")
|
||
return
|
||
except ProgrammingError:
|
||
self.stdout.write("Пропуск импорта SQL: таблицы ещё не созданы")
|
||
return
|
||
|
||
self.stdout.write(f"Импорт SQL-дампа {path}")
|
||
tables = (
|
||
AddressObject._meta.db_table,
|
||
House._meta.db_table,
|
||
)
|
||
archive = None
|
||
try:
|
||
archive, raw = open_sql_dump(path)
|
||
with transaction.atomic(), connection.cursor() as cursor:
|
||
cursor.execute("SET statement_timeout = 0")
|
||
keys = listed_foreign_keys(cursor, tables)
|
||
drop_foreign_keys(cursor, keys)
|
||
apply_pg_dump(cursor, TextIOWrapper(raw, encoding="utf-8", newline=""))
|
||
restore_foreign_keys(cursor, keys)
|
||
except Exception as exc:
|
||
raise CommandError(f"Не удалось импортировать {path}: {exc}") from exc
|
||
finally:
|
||
if archive is not None:
|
||
archive.close()
|
||
|
||
self.stdout.write(self.style.SUCCESS("SQL-дамп загружен"))
|