Fix migration to handle case where users table already exists

This commit is contained in:
Automated Action 2025-05-16 01:04:23 +00:00
parent 1710f43c85
commit 0c2239fb90

View File

@ -16,54 +16,102 @@ depends_on = None
def upgrade(): def upgrade():
# Create users table # Create users table if it doesn't exist
op.create_table( from sqlalchemy.exc import OperationalError
'users', try:
sa.Column('id', sa.Integer(), nullable=False), # Use inspector to check if the table exists
sa.Column('email', sa.String(), nullable=False), from sqlalchemy import inspect
sa.Column('username', sa.String(), nullable=False), conn = op.get_bind()
sa.Column('hashed_password', sa.String(), nullable=False), inspector = inspect(conn)
sa.Column('is_active', sa.Boolean(), nullable=True, default=True), if 'users' not in inspector.get_table_names():
sa.Column('is_superuser', sa.Boolean(), nullable=True, default=False), op.create_table(
sa.Column( 'users',
'created_at', sa.Column('id', sa.Integer(), nullable=False),
sa.DateTime(timezone=True), sa.Column('email', sa.String(), nullable=False),
server_default=sa.text('(CURRENT_TIMESTAMP)'), sa.Column('username', sa.String(), nullable=False),
nullable=True, sa.Column('hashed_password', sa.String(), nullable=False),
), sa.Column('is_active', sa.Boolean(), nullable=True, default=True),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), sa.Column('is_superuser', sa.Boolean(), nullable=True, default=False),
sa.PrimaryKeyConstraint('id'), sa.Column(
) 'created_at',
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) sa.DateTime(timezone=True),
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) server_default=sa.text('(CURRENT_TIMESTAMP)'),
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) nullable=True,
),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
except OperationalError:
# Table already exists, skip creation
pass
# Add owner_id column to todos table # Add owner_id column to todos table if it doesn't exist
op.add_column('todos', sa.Column('owner_id', sa.Integer(), nullable=True)) from sqlalchemy.exc import OperationalError
# Create foreign key from todos to users # Check if owner_id column exists in todos table
op.create_foreign_key( conn = op.get_bind()
'fk_todos_owner_id_users', inspector = inspect(conn)
'todos', 'users', columns = [col['name'] for col in inspector.get_columns('todos')]
['owner_id'], ['id'],
)
# Update all existing todos to have owner_id = 1 (first user) if 'owner_id' not in columns:
op.execute("UPDATE todos SET owner_id = 1") try:
op.add_column('todos', sa.Column('owner_id', sa.Integer(), nullable=True))
# Make owner_id non-nullable after updating existing todos # Create foreign key from todos to users
op.alter_column('todos', 'owner_id', nullable=False) op.create_foreign_key(
'fk_todos_owner_id_users',
'todos', 'users',
['owner_id'], ['id'],
)
# Update all existing todos to have owner_id = 1 (first user)
op.execute("UPDATE todos SET owner_id = 1")
# Make owner_id non-nullable after updating existing todos
op.alter_column('todos', 'owner_id', nullable=False)
except OperationalError as e:
# Log the error but continue
print(f"Operation failed with error: {str(e)}")
# If this is because the column already exists, we can continue
pass
def downgrade(): def downgrade():
# Drop foreign key constraint from sqlalchemy import inspect
op.drop_constraint('fk_todos_owner_id_users', 'todos', type_='foreignkey') from sqlalchemy.exc import OperationalError
# Drop owner_id column from todos conn = op.get_bind()
op.drop_column('todos', 'owner_id') inspector = inspect(conn)
# Drop users table # Check if the constraint exists before trying to drop it
op.drop_index(op.f('ix_users_username'), table_name='users') try:
op.drop_index(op.f('ix_users_id'), table_name='users') constraints = inspector.get_foreign_keys('todos')
op.drop_index(op.f('ix_users_email'), table_name='users') constraint_name = 'fk_todos_owner_id_users'
op.drop_table('users') fk_exists = any(constraint['name'] == constraint_name for constraint in constraints)
if fk_exists:
op.drop_constraint('fk_todos_owner_id_users', 'todos', type_='foreignkey')
except OperationalError:
pass
# Check if owner_id column exists before trying to drop it
columns = [col['name'] for col in inspector.get_columns('todos')]
if 'owner_id' in columns:
op.drop_column('todos', 'owner_id')
# Check if users table exists before trying to drop it
if 'users' in inspector.get_table_names():
# Check for each index before dropping
indices = inspector.get_indexes('users')
index_names = [index['name'] for index in indices]
if 'ix_users_username' in index_names:
op.drop_index(op.f('ix_users_username'), table_name='users')
if 'ix_users_id' in index_names:
op.drop_index(op.f('ix_users_id'), table_name='users')
if 'ix_users_email' in index_names:
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')