pyfedi/migrations/versions/fdaeb0b2c078_user_stats.py
2024-09-13 11:08:04 +12:00

55 lines
1.5 KiB
Python

"""user stats
Revision ID: fdaeb0b2c078
Revises: 2cae414cbc7a
Create Date: 2024-09-13 09:37:24.847306
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fdaeb0b2c078'
down_revision = '2cae414cbc7a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.add_column(sa.Column('post_count', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('post_reply_count', sa.Integer(), nullable=True))
# ### end Alembic commands ###
op.execute(sa.DDL('UPDATE "user" SET post_count = 0, post_reply_count = 0'))
op.execute(sa.DDL("""UPDATE "user"
SET post_count = subquery.post_count
FROM (
SELECT user_id, COUNT(*) as post_count
FROM post
WHERE deleted = false
GROUP BY user_id
) AS subquery
WHERE "user".id = subquery.user_id;"""))
op.execute(sa.DDL("""UPDATE "user"
SET post_reply_count = subquery.post_count
FROM (
SELECT user_id, COUNT(*) as post_count
FROM post_reply
WHERE deleted = false
GROUP BY user_id
) AS subquery
WHERE "user".id = subquery.user_id;"""))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_column('post_reply_count')
batch_op.drop_column('post_count')
# ### end Alembic commands ###