homelab_automation/alembic/versions/0012_add_docker_unique_constraints.py
Bruno Charest 984d06a223
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
feat: Implement comprehensive database schema with new models, CRUD operations, and documentation for host metrics, Docker management, and terminal sessions, while removing old test files.
2026-03-05 10:16:13 -05:00

87 lines
2.5 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 id FROM (
SELECT MAX(id) AS id FROM docker_containers
GROUP BY host_id, container_id
) AS tmp
)
""")
# 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 id FROM (
SELECT MAX(id) AS id FROM docker_images
GROUP BY host_id, image_id
) AS tmp
)
""")
# For docker_volumes: keep only the most recent entry per (host_id, name)
op.execute("""
DELETE FROM docker_volumes
WHERE id NOT IN (
SELECT id FROM (
SELECT MAX(id) AS id FROM docker_volumes
GROUP BY host_id, name
) AS tmp
)
""")
# 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')