|
| 1 | +from typing import Optional |
| 2 | +import os |
| 3 | +from .config import DBConfig |
| 4 | +from .logger import logger |
| 5 | + |
| 6 | +from dotenv import load_dotenv |
| 7 | + |
| 8 | +from .base_connector import BaseConnector |
| 9 | + |
| 10 | +from .clickhouse_connector import ClickHouseConnector |
| 11 | +from .postgres_connector import PostgresConnector |
| 12 | +from .mysql_connector import MySQLConnector |
| 13 | +from .mariadb_connector import MariaDBConnector |
| 14 | +from .oracle_connector import OracleConnector |
| 15 | +from .duckdb_connector import DuckDBConnector |
| 16 | +from .databricks_connector import DatabricksConnector |
| 17 | +from .snowflake_connector import SnowflakeConnector |
| 18 | + |
| 19 | +env_path = os.path.join(os.getcwd(), ".env") |
| 20 | + |
| 21 | +if os.path.exists(env_path): |
| 22 | + load_dotenv(env_path, override=True) |
| 23 | + print(f"✅ 환경변수 파일(.env)이 {os.getcwd()}에 로드되었습니다!") |
| 24 | +else: |
| 25 | + print(f"⚠️ 환경변수 파일(.env)이 {os.getcwd()}에 없습니다!") |
| 26 | + |
| 27 | + |
| 28 | +def get_db_connector(db_type: Optional[str] = None, config: Optional[DBConfig] = None): |
| 29 | + """ |
| 30 | + Return the appropriate DB connector instance. |
| 31 | + - If db_type is not provided, loads from environment variable DB_TYPE |
| 32 | + - If config is not provided, loads from environment using db_type |
| 33 | +
|
| 34 | + Parameters: |
| 35 | + db_type (Optional[str]): Database type (e.g., 'postgresql', 'mysql') |
| 36 | + config (Optional[DBConfig]): Connection config |
| 37 | +
|
| 38 | + Returns: |
| 39 | + BaseConnector: Initialized DB connector instance |
| 40 | +
|
| 41 | + Raises: |
| 42 | + ValueError: If type/config is missing or invalid |
| 43 | + """ |
| 44 | + if db_type is None: |
| 45 | + db_type = os.getenv("DB_TYPE") |
| 46 | + if not db_type: |
| 47 | + raise ValueError( |
| 48 | + "DB type must be provided or set in environment as DB_TYPE." |
| 49 | + ) |
| 50 | + |
| 51 | + db_type = db_type.lower() |
| 52 | + |
| 53 | + if config is None: |
| 54 | + config = load_config_from_env(db_type.upper()) |
| 55 | + |
| 56 | + connector_map = { |
| 57 | + "clickhouse": ClickHouseConnector, |
| 58 | + "postgresql": PostgresConnector, |
| 59 | + "mysql": MySQLConnector, |
| 60 | + "mariadb": MariaDBConnector, |
| 61 | + "oracle": OracleConnector, |
| 62 | + "duckdb": DuckDBConnector, |
| 63 | + "databricks": DatabricksConnector, |
| 64 | + "snowflake": SnowflakeConnector, |
| 65 | + } |
| 66 | + |
| 67 | + if db_type not in connector_map: |
| 68 | + logger.error(f"Unsupported DB type: {db_type}") |
| 69 | + raise ValueError(f"Unsupported DB type: {db_type}") |
| 70 | + |
| 71 | + required_fields = { |
| 72 | + "oracle": ["extra.service_name"], |
| 73 | + "databricks": ["extra.http_path", "extra.access_token"], |
| 74 | + "snowflake": ["extra.account"], |
| 75 | + } |
| 76 | + |
| 77 | + missing = [] |
| 78 | + for path in required_fields.get(db_type, []): |
| 79 | + cur = config |
| 80 | + for key in path.split("."): |
| 81 | + cur = cur.get(key) if isinstance(cur, dict) else None |
| 82 | + if cur is None: |
| 83 | + missing.append(path) |
| 84 | + break |
| 85 | + |
| 86 | + if missing: |
| 87 | + logger.error(f"Missing required fields for {db_type}: {', '.join(missing)}") |
| 88 | + raise ValueError(f"Missing required fields for {db_type}: {', '.join(missing)}") |
| 89 | + |
| 90 | + return connector_map[db_type](config) |
| 91 | + |
| 92 | + |
| 93 | +def load_config_from_env(prefix: str) -> DBConfig: |
| 94 | + """ |
| 95 | + Load DBConfig from environment variables with a given prefix. |
| 96 | + Standard keys are extracted, all other prefixed keys go to 'extra'. |
| 97 | +
|
| 98 | + Example: |
| 99 | + If prefix = 'SNOWFLAKE', loads: |
| 100 | + - SNOWFLAKE_HOST |
| 101 | + - SNOWFLAKE_USER |
| 102 | + - SNOWFLAKE_PASSWORD |
| 103 | + - SNOWFLAKE_PORT |
| 104 | + - SNOWFLAKE_DATABASE |
| 105 | + Other keys like SNOWFLAKE_ACCOUNT, SNOWFLAKE_WAREHOUSE -> extra |
| 106 | + """ |
| 107 | + base_keys = {"HOST", "PORT", "USER", "PASSWORD", "DATABASE"} |
| 108 | + |
| 109 | + # Extract standard values |
| 110 | + config = { |
| 111 | + "host": os.getenv(f"{prefix}_HOST"), |
| 112 | + "port": ( |
| 113 | + int(os.getenv(f"{prefix}_PORT")) if os.getenv(f"{prefix}_PORT") else None |
| 114 | + ), |
| 115 | + "user": os.getenv(f"{prefix}_USER"), |
| 116 | + "password": os.getenv(f"{prefix}_PASSWORD"), |
| 117 | + "database": os.getenv(f"{prefix}_DATABASE"), |
| 118 | + } |
| 119 | + |
| 120 | + # Auto-detect extra keys |
| 121 | + extra = {} |
| 122 | + for key, value in os.environ.items(): |
| 123 | + if key.startswith(f"{prefix}_"): |
| 124 | + suffix = key[len(f"{prefix}_") :] |
| 125 | + if suffix.upper() not in base_keys: |
| 126 | + extra[suffix.lower()] = value |
| 127 | + |
| 128 | + if extra: |
| 129 | + config["extra"] = extra |
| 130 | + |
| 131 | + return DBConfig(**config) |
0 commit comments