utils.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from alembic import op
  2. import sqlalchemy as sa
  3. from sqlalchemy.engine.reflection import Inspector
  4. def is_opengauss(conn) -> bool:
  5. """Check if the database is openGauss (presents as postgresql dialect).
  6. openGauss is a PostgreSQL-compatible database that lacks certain aggregate
  7. functions such as jsonb_agg and set-returning functions like
  8. jsonb_array_elements. Migrations that use those functions must detect this
  9. and fall back to Python-based processing instead.
  10. """
  11. if conn.dialect.name != 'postgresql':
  12. return False
  13. try:
  14. version = conn.execute(sa.text("SELECT version()")).scalar()
  15. return 'openGauss' in (version or '')
  16. except Exception:
  17. return False
  18. def column_exists(table_name, column_name) -> bool:
  19. """Check if a column exists in a table.
  20. Args:
  21. table_name (str): The name of the table.
  22. column_name (str): The name of the column.
  23. Returns:
  24. bool: True if the column exists, False otherwise.
  25. """
  26. conn = op.get_bind()
  27. inspector = Inspector.from_engine(conn)
  28. columns = [col["name"] for col in inspector.get_columns(table_name)]
  29. return column_name in columns
  30. def table_exists(table_name) -> bool:
  31. """Check if a table exists in the database.
  32. Args:
  33. table_name (str): The name of the table."
  34. Returns:
  35. bool: True if the table exists, False otherwise.
  36. """
  37. conn = op.get_bind()
  38. inspector = Inspector.from_engine(conn)
  39. return table_name in inspector.get_table_names()