diff --git a/reana_db/alembic/versions/20240531_0959_86435bb00714_foreign_key_for_workflow_uuid_of_job.py b/reana_db/alembic/versions/20240531_0959_86435bb00714_foreign_key_for_workflow_uuid_of_job.py new file mode 100644 index 0000000..bf8d11c --- /dev/null +++ b/reana_db/alembic/versions/20240531_0959_86435bb00714_foreign_key_for_workflow_uuid_of_job.py @@ -0,0 +1,64 @@ +"""Foreign key for workflow_uuid of Job. + +Revision ID: 86435bb00714 +Revises: eb5309f3d8ee +Create Date: 2024-05-31 09:59:18.951074 + +""" + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = "86435bb00714" +down_revision = "eb5309f3d8ee" +branch_labels = None +depends_on = None + + +def upgrade(): + """Upgrade to 86435bb00714.""" + job_table = sa.sql.table("job", sa.sql.column("workflow_uuid"), schema="__reana") + workflow_table = sa.sql.table("workflow", sa.sql.column("id_"), schema="__reana") + + # 1. delete jobs which refer to non-existing workflows + op.execute( + job_table.delete().where( + job_table.c.workflow_uuid.notin_(sa.select([workflow_table.c.id_])) + ) + ) + + # 2. alter column to make it non-nullable + op.alter_column( + "job", + "workflow_uuid", + existing_type=postgresql.UUID(), + nullable=False, + schema="__reana", + ) + + # 3. create foreign key constraint + op.create_foreign_key( + "fk_job_workflow_uuid_workflow", + "job", + "workflow", + ["workflow_uuid"], + ["id_"], + source_schema="__reana", + referent_schema="__reana", + ) + + +def downgrade(): + """Downgrade to eb5309f3d8ee.""" + op.drop_constraint( + "fk_job_workflow_uuid_workflow", "job", schema="__reana", type_="foreignkey" + ) + op.alter_column( + "job", + "workflow_uuid", + existing_type=postgresql.UUID(), + nullable=True, + schema="__reana", + ) diff --git a/reana_db/models.py b/reana_db/models.py index 36609fc..c0b0206 100644 --- a/reana_db/models.py +++ b/reana_db/models.py @@ -823,7 +823,11 @@ class Job(Base, Timestamp): id_ = Column(UUIDType, primary_key=True, default=generate_uuid) backend_job_id = Column(String(256)) - workflow_uuid = Column(UUIDType) + workflow_uuid = Column( + UUIDType, + ForeignKey("__reana.workflow.id_"), + nullable=False, + ) status = Column(Enum(JobStatus), default=JobStatus.created) compute_backend = Column(String(30)) cvmfs_mounts = Column(Text)