Update comment count migration, calculate initial counts during upgrade

How fancy!
This commit is contained in:
TheAMM 2017-05-27 22:46:35 +03:00
parent 16194a12a3
commit 2d04cf3525
1 changed files with 20 additions and 12 deletions

View File

@ -15,30 +15,38 @@ down_revision = 'd0eeb8049623'
branch_labels = None
depends_on = None
COMMENT_UPDATE_SQL = '''UPDATE {0}_torrents
SET comment_count = (
SELECT COUNT(*) FROM {0}_comments
WHERE {0}_torrents.id = {0}_comments.torrent_id
);'''
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('nyaa_torrents', sa.Column('comment_count', sa.Integer(), nullable=False))
op.create_index(op.f('ix_nyaa_torrents_comment_count'), 'nyaa_torrents', ['comment_count'], unique=False)
try:
op.add_column('sukebei_torrents', sa.Column('comment_count', sa.Integer(), nullable=False))
op.create_index(op.f('ix_sukebei_torrents_comment_count'), 'sukebei_torrents', ['comment_count'], unique=False)
except (sa.exc.OperationalError, sa.exc.ProgrammingError):
print('Could not upgrade sukebei!')
op.add_column('sukebei_torrents', sa.Column('comment_count', sa.Integer(), nullable=False))
op.create_index(op.f('ix_sukebei_torrents_comment_count'), 'sukebei_torrents', ['comment_count'], unique=False)
# ### end Alembic commands ###
connection = op.get_bind()
print('Updating comment counts on nyaa_torrents...')
connection.execute(sa.sql.text(COMMENT_UPDATE_SQL.format('nyaa')))
print('Done.')
print('Updating comment counts on sukebei_torrents...')
connection.execute(sa.sql.text(COMMENT_UPDATE_SQL.format('sukebei')))
print('Done.')
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_nyaa_torrents_comment_count'), table_name='nyaa_torrents')
op.drop_column('nyaa_torrents', 'comment_count')
try:
op.drop_index(op.f('ix_sukebei_torrents_comment_count'), table_name='sukebei_torrents')
op.drop_column('sukebei_torrents', 'comment_count')
except (sa.exc.OperationalError, sa.exc.ProgrammingError):
print('Could not downgrade sukebei!')
op.drop_index(op.f('ix_sukebei_torrents_comment_count'), table_name='sukebei_torrents')
op.drop_column('sukebei_torrents', 'comment_count')
# ### end Alembic commands ###