説明なし

alembic_utils.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from alembic import op
  2. from sqlalchemy import engine_from_config
  3. from sqlalchemy.engine import reflection
  4. from sqlalchemy import text
  5. def _table_has_column(table, column):
  6. config = op.get_context().config
  7. engine = engine_from_config(
  8. config.get_section(config.config_ini_section), prefix='sqlalchemy.')
  9. connection = engine.connect()
  10. try:
  11. result = connection.execute(text(f"SELECT * FROM \"{table}\" LIMIT 1"))
  12. columns = result.keys()
  13. except Exception:
  14. return False
  15. finally:
  16. connection.close()
  17. has_column = column in columns
  18. return has_column
  19. def _has_table(table_name):
  20. config = op.get_context().config
  21. engine = engine_from_config(
  22. config.get_section(config.config_ini_section), prefix="sqlalchemy."
  23. )
  24. inspector = reflection.Inspector.from_engine(engine)
  25. tables = inspector.get_table_names()
  26. return table_name in tables
  27. def index_exists(table_name, index_name):
  28. config = op.get_context().config
  29. engine = engine_from_config(
  30. config.get_section(config.config_ini_section), prefix="sqlalchemy."
  31. )
  32. inspector = reflection.Inspector.from_engine(engine)
  33. indexes = inspector.get_indexes(table_name)
  34. return any(index['name'] == index_name for index in indexes)