homelab_automation/alembic/versions/0012_add_docker_unique_constraints.py
Bruno Charest 68a9b0f390
Some checks failed
Tests / Backend Tests (Python) (3.10) (push) Has been cancelled
Tests / Backend Tests (Python) (3.11) (push) Has been cancelled
Tests / Backend Tests (Python) (3.12) (push) Has been cancelled
Tests / Frontend Tests (JS) (push) Has been cancelled
Tests / Integration Tests (push) Has been cancelled
Tests / All Tests Passed (push) Has been cancelled
Remove Node.js cache files containing npm vulnerability data for vitest and vite packages
2025-12-15 20:36:06 -05:00

81 lines
2.3 KiB
Python

"""Add unique constraints to Docker tables.
Revision ID: 0012
Revises: 0011
Create Date: 2025-12-15
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '0012'
down_revision: Union[str, None] = '0011_add_docker_management_tables'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Add unique constraints to Docker tables to prevent duplicates."""
# First, clean up any existing duplicates before adding constraints
# For docker_containers: keep only the most recent entry per (host_id, container_id)
op.execute("""
DELETE FROM docker_containers
WHERE id NOT IN (
SELECT MAX(id) FROM docker_containers
GROUP BY host_id, container_id
)
""")
# For docker_images: keep only the most recent entry per (host_id, image_id)
op.execute("""
DELETE FROM docker_images
WHERE id NOT IN (
SELECT MAX(id) FROM docker_images
GROUP BY host_id, image_id
)
""")
# For docker_volumes: keep only the most recent entry per (host_id, name)
op.execute("""
DELETE FROM docker_volumes
WHERE id NOT IN (
SELECT MAX(id) FROM docker_volumes
GROUP BY host_id, name
)
""")
# Now add unique constraints
# Note: SQLite doesn't support adding constraints directly, so we use CREATE UNIQUE INDEX
op.create_index(
'uq_docker_containers_host_container',
'docker_containers',
['host_id', 'container_id'],
unique=True
)
op.create_index(
'uq_docker_images_host_image',
'docker_images',
['host_id', 'image_id'],
unique=True
)
op.create_index(
'uq_docker_volumes_host_name',
'docker_volumes',
['host_id', 'name'],
unique=True
)
def downgrade() -> None:
"""Remove unique constraints from Docker tables."""
op.drop_index('uq_docker_containers_host_container', table_name='docker_containers')
op.drop_index('uq_docker_images_host_image', table_name='docker_images')
op.drop_index('uq_docker_volumes_host_name', table_name='docker_volumes')