Files
life-echo/api/alembic/script_helpers.py
2026-05-19 16:40:45 +08:00

35 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Alembic 迁移共享工具(仅用于 versions/ 下的迁移脚本)。"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
def table_exists(table_name: str) -> bool:
bind = op.get_bind()
return table_name in sa.inspect(bind).get_table_names()
def has_column(table_name: str, column_name: str) -> bool:
if not table_exists(table_name):
return False
bind = op.get_bind()
columns = sa.inspect(bind).get_columns(table_name)
return any(column["name"] == column_name for column in columns)
def add_column_if_missing(table_name: str, column: sa.Column) -> bool:
"""若列不存在则 add_column返回是否执行了添加。"""
if has_column(table_name, column.name):
return False
op.add_column(table_name, column)
return True
def drop_column_if_exists(table_name: str, column_name: str) -> bool:
if not has_column(table_name, column_name):
return False
op.drop_column(table_name, column_name)
return True