summaryrefslogtreecommitdiff
path: root/migrations/versions/30bfe33aa328_add_file_size_field.py
blob: e6ac279b46905b2beef543954aa7e5f55624d5d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""add file size field

Revision ID: 30bfe33aa328
Revises: 5cee97aab219
Create Date: 2022-12-13 22:32:12.242394

"""

# revision identifiers, used by Alembic.
revision = '30bfe33aa328'
down_revision = '5cee97aab219'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from flask import current_app
from pathlib import Path

Base = automap_base()

def upgrade():
    op.add_column('file', sa.Column('size', sa.BigInteger(), nullable=True))
    bind = op.get_bind()
    Base.prepare(autoload_with=bind)
    File = Base.classes.file
    session = Session(bind=bind)

    storage = Path(current_app.config["FHOST_STORAGE_PATH"])

    updates = []
    files = session.scalars(sa.select(File).where(sa.not_(File.removed)))
    for f in files:
        p = storage / f.sha256
        if p.is_file():
            updates.append({
                "id" : f.id,
                "size" : p.stat().st_size
            })

    session.bulk_update_mappings(File, updates)
    session.commit()


def downgrade():
    op.drop_column('file', 'size')