"""Env methods.""" import os import subprocess from ..configs import DBConfig, MySQLConfig, SnowflakeConfig from ..errors import ConfigurationError, GenerationError def check_sqlacodegen() -> bool: """Check if sqlacodegen is installed.""" try: subprocess.run(['sqlacodegen', '--version'], capture_output=True, check=True) return True except (subprocess.CalledProcessError, FileNotFoundError): return False def get_db_config() -> DBConfig: """Get the database config.""" try_vars(['DB_VENDOR']) vendor = str(os.environ.get('DB_VENDOR')).lower() if vendor == 'mysql': return get_mysql_config() if vendor == 'snowflake': return get_snowflake_config() raise ValueError(f"Unknown DB vendor '{vendor}. Supported: mysql, snowflake") def get_mysql_config() -> MySQLConfig: """Get the MySQL configuration from environment variables.""" try_vars(['DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME']) return MySQLConfig( host=str(os.environ.get('DB_HOST')), user=str(os.environ.get('DB_USER')), password=str(os.environ.get('DB_PASS')), database=str(os.environ.get('DB_NAME')), port=int(os.environ.get('DB_PORT', '3306')), ) def get_snowflake_config() -> SnowflakeConfig: """Get the MySQL configuration from environment variables.""" try_vars(['DB_ACCOUNT', 'DB_NAME']) return SnowflakeConfig( account=str(os.environ.get('DB_ACCOUNT')), user=str(os.environ.get('DB_USER')), role=str(os.environ.get('DB_ROLE')), database=str(os.environ.get('DB_NAME')), password=os.environ.get('DB_PASS'), private_key_path=os.environ.get('DB_KEY_PATH'), private_key_pass=os.environ.get('DB_KEY_PASS'), schema=os.environ.get('DB_SCHEMA'), warehouse=os.environ.get('DB_WAREHOUSE'), ) def try_env() -> None: """Run all environment checks.""" try_sqlacodegen() def try_sqlacodegen() -> None: """Raise an error if sqlacodegen is not installed.""" if not check_sqlacodegen(): raise GenerationError('sqlacodegen is not installed') def try_vars(required: list[str]) -> None: """Check for env vars and raise if any are missing.""" missing = [var for var in required if var not in os.environ] if missing: raise ConfigurationError(f'Missing required env vars: {", ".join(missing)}')