homelab_automation/alembic/versions/0010_remove_logs_foreign_keys.py

62 lines
2.0 KiB
Python

"""Remove foreign key constraints from logs table.
Revision ID: 0010
Revises: 0009_add_app_settings_table
Create Date: 2025-12-14
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0010_remove_logs_foreign_keys'
down_revision = '0009_add_app_settings_table'
branch_labels = None
depends_on = None
def upgrade():
"""Remove FK constraints from logs table by recreating it."""
# SQLite doesn't support ALTER TABLE DROP CONSTRAINT
# We need to recreate the table without the FK constraints
# Create new table without FK constraints
op.create_table(
'logs_new',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('level', sa.String(), nullable=False),
sa.Column('source', sa.String(), nullable=True),
sa.Column('message', sa.Text(), nullable=False),
sa.Column('details', sa.JSON(), nullable=True),
sa.Column('host_id', sa.String(), nullable=True),
sa.Column('task_id', sa.String(), nullable=True),
sa.Column('schedule_id', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# Copy data from old table
op.execute('''
INSERT INTO logs_new (id, level, source, message, details, host_id, task_id, schedule_id, created_at)
SELECT id, level, source, message, details, host_id, task_id, schedule_id, created_at FROM logs
''')
# Drop old table
op.drop_table('logs')
# Rename new table
op.rename_table('logs_new', 'logs')
# Recreate indexes
op.create_index('idx_logs_created_at', 'logs', ['created_at'])
op.create_index('idx_logs_level', 'logs', ['level'])
op.create_index('idx_logs_source', 'logs', ['source'])
def downgrade():
"""Restore FK constraints (not recommended)."""
# This would require recreating with FK constraints
# For simplicity, we don't implement downgrade
pass