66 lines
2.2 KiB
Python
66 lines
2.2 KiB
Python
from collections.abc import Iterable, Iterator
|
||
from pathlib import Path
|
||
from zipfile import ZipFile
|
||
|
||
from django.db.backends.utils import CursorWrapper
|
||
|
||
SQL_MEMBER_SUFFIX = ".sql"
|
||
|
||
|
||
def sql_member_name(names: Iterable[str]) -> str:
|
||
for name in names:
|
||
if (
|
||
name.endswith(SQL_MEMBER_SUFFIX)
|
||
and not Path(name).name.startswith(".")
|
||
and not name.startswith("__MACOSX/")
|
||
):
|
||
return name
|
||
raise FileNotFoundError("В архиве нет SQL-файла")
|
||
|
||
|
||
def open_sql_dump(path: Path):
|
||
archive = ZipFile(path)
|
||
try:
|
||
return archive, archive.open(sql_member_name(archive.namelist()))
|
||
except Exception:
|
||
archive.close()
|
||
raise
|
||
|
||
|
||
def listed_foreign_keys(cursor: CursorWrapper, tables: tuple[str, ...]) -> list[tuple[str, str, str]]:
|
||
placeholders = ", ".join(["%s::regclass"] * len(tables))
|
||
cursor.execute(
|
||
f"""
|
||
SELECT conrelid::regclass::text, conname, pg_get_constraintdef(oid)
|
||
FROM pg_constraint
|
||
WHERE contype = 'f' AND conrelid IN ({placeholders})
|
||
""",
|
||
list(tables),
|
||
)
|
||
return [(table, name, definition) for table, name, definition in cursor.fetchall()]
|
||
|
||
|
||
def drop_foreign_keys(cursor: CursorWrapper, keys: list[tuple[str, str, str]]) -> None:
|
||
for table, name, _definition in keys:
|
||
cursor.execute(f'ALTER TABLE {table} DROP CONSTRAINT "{name}"')
|
||
|
||
|
||
def restore_foreign_keys(cursor: CursorWrapper, keys: list[tuple[str, str, str]]) -> None:
|
||
for table, name, definition in keys:
|
||
cursor.execute(f'ALTER TABLE {table} ADD CONSTRAINT "{name}" {definition}')
|
||
|
||
|
||
def apply_pg_dump(cursor: CursorWrapper, lines: Iterator[str]) -> None:
|
||
for line in lines:
|
||
stripped = line.strip()
|
||
if stripped.upper().startswith("COPY ") and stripped.lower().endswith("from stdin;"):
|
||
copy_sql = stripped[:-1].replace("FROM stdin", "FROM STDIN")
|
||
with cursor.copy(copy_sql) as copy:
|
||
for row in lines:
|
||
if row in {"\\.\n", "\\.\r\n", "\\."}:
|
||
break
|
||
copy.write(row)
|
||
continue
|
||
if stripped.startswith("SELECT pg_catalog.setval"):
|
||
cursor.execute(stripped if stripped.endswith(";") else f"{stripped};")
|