|
| 1 | +""" |
| 2 | +
|
| 3 | +Revision ID: 0483_index_jobs |
| 4 | +Revises: 0482_index_facts |
| 5 | +Create Date: 2025-06-09 20:01:02.943393 |
| 6 | +
|
| 7 | +""" |
| 8 | +from alembic import op |
| 9 | + |
| 10 | +revision = '0483_index_jobs' |
| 11 | +down_revision = '0482_index_facts' |
| 12 | + |
| 13 | +def index_exists(name): |
| 14 | + connection = op.get_bind() |
| 15 | + result = connection.execute( |
| 16 | + "SELECT exists(SELECT 1 from pg_indexes where indexname = '{}') as ix_exists;".format(name) |
| 17 | + ).first() |
| 18 | + return result.ix_exists |
| 19 | + |
| 20 | +def upgrade(): |
| 21 | + # PostgreSQL requires that CREATE INDEX CONCURRENTLY cannot run within a transaction. |
| 22 | + # Alembic runs migrations in a transaction by default, so we need to commit the current |
| 23 | + # transaction before creating indexes concurrently. |
| 24 | + op.execute("COMMIT") |
| 25 | + if not index_exists("ix_jobs_created_at"): |
| 26 | + op.create_index( |
| 27 | + op.f('ix_jobs_created_at'), |
| 28 | + 'jobs', |
| 29 | + ['created_at'], |
| 30 | + unique=False, |
| 31 | + postgresql_concurrently=True |
| 32 | + ) |
| 33 | + if not index_exists("ix_jobs_processing_started"): |
| 34 | + op.create_index( |
| 35 | + op.f('ix_jobs_processing_started'), |
| 36 | + 'jobs', |
| 37 | + ['processing_started'], |
| 38 | + unique=False, |
| 39 | + postgresql_concurrently=True |
| 40 | + ) |
| 41 | + |
| 42 | + |
| 43 | +def downgrade(): |
| 44 | + # PostgreSQL requires that DROP INDEX CONCURRENTLY cannot run within a transaction. |
| 45 | + # Need to commit the current transaction first. |
| 46 | + op.execute("COMMIT") |
| 47 | + if index_exists("ix_jobs_processing_started"): |
| 48 | + op.drop_index( |
| 49 | + op.f('ix_jobs_processing_started'), |
| 50 | + table_name='jobs', |
| 51 | + postgresql_concurrently=True |
| 52 | + ) |
| 53 | + if index_exists("ix_jobs_created_at"): |
| 54 | + op.drop_index( |
| 55 | + op.f('ix_jobs_created_at'), |
| 56 | + table_name='jobs', |
| 57 | + postgresql_concurrently=True |
| 58 | + ) |
0 commit comments