|
| 1 | +# SPDX-FileCopyrightText: 2024-2025 MTS PJSC |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +"""Add job_type |
| 4 | +
|
| 5 | +Revision ID: 2d2fe3f2f348 |
| 6 | +Revises: 976168ee4f16 |
| 7 | +Create Date: 2025-04-25 15:09:17.556969 |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +import sqlalchemy as sa |
| 12 | +from alembic import op |
| 13 | + |
| 14 | +# revision identifiers, used by Alembic. |
| 15 | +revision = "2d2fe3f2f348" |
| 16 | +down_revision = "976168ee4f16" |
| 17 | +branch_labels = None |
| 18 | +depends_on = None |
| 19 | + |
| 20 | + |
| 21 | +def upgrade() -> None: |
| 22 | + op.create_table( |
| 23 | + "job_type", |
| 24 | + sa.Column("id", sa.BigInteger(), nullable=False), |
| 25 | + sa.Column("type", sa.String(), nullable=False), |
| 26 | + sa.PrimaryKeyConstraint("id", name=op.f("pk__job_type")), |
| 27 | + sa.UniqueConstraint("type", name=op.f("uq__job_type__type")), |
| 28 | + ) |
| 29 | + op.create_index(op.f("ix__job_type__type"), "job_type", ["type"], unique=False) |
| 30 | + |
| 31 | + op.execute( |
| 32 | + sa.text( |
| 33 | + """ |
| 34 | + INSERT INTO |
| 35 | + job_type (id, type) |
| 36 | + VALUES |
| 37 | + (0, 'UNKNOWN'), |
| 38 | + (1, 'SPARK_APPLICATION'), |
| 39 | + (2, 'AIRFLOW_DAG'), |
| 40 | + (3, 'AIRFLOW_TASK'); |
| 41 | + """, |
| 42 | + ), |
| 43 | + ) |
| 44 | + op.execute(sa.text("ALTER SEQUENCE job_type_id_seq RESTART WITH 4;")) |
| 45 | + |
| 46 | + op.execute(sa.text("LOCK TABLE job IN ACCESS EXCLUSIVE MODE;")) |
| 47 | + op.drop_index("ix__job__type", table_name="job") |
| 48 | + op.alter_column( |
| 49 | + "job", |
| 50 | + "type", |
| 51 | + new_column_name="type_id", |
| 52 | + existing_type=sa.String(length=32), |
| 53 | + type_=sa.BigInteger(), |
| 54 | + nullable=False, |
| 55 | + postgresql_using=""" |
| 56 | + CASE |
| 57 | + WHEN type = 'SPARK_APPLICATION' |
| 58 | + THEN 1 |
| 59 | + WHEN type = 'AIRFLOW_DAG' |
| 60 | + THEN 2 |
| 61 | + WHEN type = 'AIRFLOW_TASK' |
| 62 | + THEN 3 |
| 63 | + ELSE 0 |
| 64 | + END |
| 65 | + """, |
| 66 | + ) |
| 67 | + op.create_index(op.f("ix__job__type_id"), "job", ["type_id"], unique=False) |
| 68 | + |
| 69 | + |
| 70 | +def downgrade() -> None: |
| 71 | + op.execute(sa.text("LOCK TABLE job IN ACCESS EXCLUSIVE MODE;")) |
| 72 | + op.drop_index(op.f("ix__job__type_id"), table_name="job") |
| 73 | + op.alter_column( |
| 74 | + "job", |
| 75 | + "type_id", |
| 76 | + new_column_name="type", |
| 77 | + existing_type=sa.BigInteger(), |
| 78 | + type_=sa.String(length=32), |
| 79 | + nullable=False, |
| 80 | + ) |
| 81 | + op.execute( |
| 82 | + sa.text( |
| 83 | + """ |
| 84 | + UPDATE job |
| 85 | + SET type = (SELECT job_type.type FROM job_type WHERE job_type.id = job.type); |
| 86 | + """, |
| 87 | + ), |
| 88 | + ) |
| 89 | + op.create_index("ix__job__type", "job", ["type"], unique=False) |
| 90 | + |
| 91 | + op.drop_index(op.f("ix__job_type__type"), table_name="job_type") |
| 92 | + op.drop_table("job_type") |
0 commit comments