Coverage for slidge/db/alembic/versions/211345c68f0b_no_upload_attachments_in_message_subdir.py: 68%
38 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-09-10 04:45 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-09-10 04:45 +0000
1"""Move files from NO_UPLOAD_PATH to NO_UPLOAD_PATH / messages
3Revision ID: 211345c68f0b
4Revises: 39ce1636571a
5Create Date: 2026-08-22 15:25:18.926618
7"""
9import logging
10import shutil
11from collections.abc import Sequence
12from pathlib import Path
14import sqlalchemy as sa
15from alembic import op
17from slidge.core import config
19# revision identifiers, used by Alembic.
20revision: str = "211345c68f0b"
21down_revision: str | None = "39ce1636571a"
22branch_labels: str | Sequence[str] | None = None
23depends_on: str | Sequence[str] | None = None
26def upgrade() -> None:
27 if config.NO_UPLOAD_PATH is None:
28 log.info(
29 "NO_UPLOAD_PATH is unset, no need to update local paths of attachments."
30 )
31 return
32 bind = op.get_bind()
33 result = bind.execute(sa.text("SELECT url FROM attachment"))
34 urls = [row[0] for row in result]
35 root = Path(config.NO_UPLOAD_PATH)
36 for url in urls:
37 suffix = url.removeprefix(config.NO_UPLOAD_URL_PREFIX)
38 _move(root, suffix)
39 op.execute(
40 sa.text(_REPLACE.format(old=config.NO_UPLOAD_URL_PREFIX, new=_get_new()))
41 )
44def downgrade() -> None:
45 raise RuntimeError("downgrades are not supported")
48def _get_new() -> str:
49 assert config.NO_UPLOAD_URL_PREFIX
50 return config.NO_UPLOAD_URL_PREFIX + "/message"
53def _move(root: Path, suffix: str) -> None:
54 src = root / suffix
55 if not src.exists():
56 log.warning("%s does not exist, can't migrate", src)
57 return
58 dest = root / "message" / suffix
59 dest.parent.mkdir(parents=True, exist_ok=True)
60 shutil.move(src, dest)
63_REPLACE = "UPDATE attachment SET url = REPLACE(url, '{old}', '{new}')"
65log = logging.getLogger(__name__)