From 2d04cf3525a359c546915a7894e5fb5a17297c0a Mon Sep 17 00:00:00 2001 From: TheAMM Date: Sat, 27 May 2017 22:46:35 +0300 Subject: [PATCH] Update comment count migration, calculate initial counts during upgrade How fancy! --- ...ceb2cb4d7c_add_comment_count_to_torrent.py | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/migrations/versions/2bceb2cb4d7c_add_comment_count_to_torrent.py b/migrations/versions/2bceb2cb4d7c_add_comment_count_to_torrent.py index aa88a8e..3114e27 100644 --- a/migrations/versions/2bceb2cb4d7c_add_comment_count_to_torrent.py +++ b/migrations/versions/2bceb2cb4d7c_add_comment_count_to_torrent.py @@ -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 ###