|
| 1 | +import os |
| 2 | +import pandas as pd |
| 3 | +from sqlalchemy import create_engine, exc |
| 4 | +from sqlalchemy.orm import sessionmaker |
| 5 | +from sqlalchemy import text |
| 6 | + |
| 7 | +from .config import db_config |
| 8 | + |
| 9 | + |
| 10 | +class DSDatabase: |
| 11 | + """A database utility class for connecting to a DesignSafe SQL database. |
| 12 | +
|
| 13 | + This class provides functionality to connect to a MySQL database using |
| 14 | + SQLAlchemy and PyMySQL. It supports executing SQL queries and returning |
| 15 | + results in different formats. |
| 16 | +
|
| 17 | + Attributes: |
| 18 | + user (str): Database username, defaults to 'dspublic'. |
| 19 | + password (str): Database password, defaults to 'R3ad0nlY'. |
| 20 | + host (str): Database host address, defaults to '129.114.52.174'. |
| 21 | + port (int): Database port, defaults to 3306. |
| 22 | + db (str): Database name, can be 'sjbrande_ngl_db', 'sjbrande_vpdb', or 'post_earthquake_recovery'. |
| 23 | + recycle_time (int): Time in seconds to recycle database connections. |
| 24 | + engine (Engine): SQLAlchemy engine for database connection. |
| 25 | + Session (sessionmaker): SQLAlchemy session maker bound to the engine. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, dbname="ngl"): |
| 29 | + """Initializes the DSDatabase instance with environment variables and creates the database engine. |
| 30 | +
|
| 31 | + Args: |
| 32 | + dbname (str): Shorthand for the database name. Must be one of 'ngl', 'vp', or 'eq'. |
| 33 | + """ |
| 34 | + |
| 35 | + if dbname not in db_config: |
| 36 | + raise ValueError( |
| 37 | + f"Invalid database shorthand '{dbname}'. Allowed shorthands are: {', '.join(db_config.keys())}" |
| 38 | + ) |
| 39 | + |
| 40 | + config = db_config[dbname] |
| 41 | + env_prefix = config["env_prefix"] |
| 42 | + |
| 43 | + self.user = os.getenv(f"{env_prefix}DB_USER", "dspublic") |
| 44 | + self.password = os.getenv(f"{env_prefix}DB_PASSWORD", "R3ad0nlY") |
| 45 | + self.host = os.getenv(f"{env_prefix}DB_HOST", "129.114.52.174") |
| 46 | + self.port = os.getenv(f"{env_prefix}DB_PORT", 3306) |
| 47 | + self.db = config["dbname"] |
| 48 | + |
| 49 | + # Setup the database connection |
| 50 | + self.engine = create_engine( |
| 51 | + f"mysql+pymysql://{self.user}:{self.password}@{self.host}:{self.port}/{self.db}", |
| 52 | + pool_recycle=3600, # 1 hour in seconds |
| 53 | + ) |
| 54 | + self.Session = sessionmaker(bind=self.engine) |
| 55 | + |
| 56 | + def read_sql(self, sql, output_type="DataFrame"): |
| 57 | + """Executes a SQL query and returns the results. |
| 58 | +
|
| 59 | + Args: |
| 60 | + sql (str): The SQL query string to be executed. |
| 61 | + output_type (str, optional): The format for the query results. Defaults to 'DataFrame'. |
| 62 | + Possible values are 'DataFrame' for a pandas DataFrame, or 'dict' for a list of dictionaries. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + pandas.DataFrame or list of dict: The result of the SQL query. |
| 66 | +
|
| 67 | + Raises: |
| 68 | + ValueError: If the SQL query string is empty or if the output type is not valid. |
| 69 | + SQLAlchemyError: If an error occurs during query execution. |
| 70 | + """ |
| 71 | + if not sql: |
| 72 | + raise ValueError("SQL query string is required") |
| 73 | + |
| 74 | + if output_type not in ["DataFrame", "dict"]: |
| 75 | + raise ValueError('Output type must be either "DataFrame" or "dict"') |
| 76 | + |
| 77 | + session = self.Session() |
| 78 | + |
| 79 | + try: |
| 80 | + if output_type == "DataFrame": |
| 81 | + return pd.read_sql_query(sql, session.bind) |
| 82 | + else: |
| 83 | + # Convert SQL string to a text object |
| 84 | + sql_text = text(sql) |
| 85 | + result = session.execute(sql_text) |
| 86 | + return [dict(row) for row in result] |
| 87 | + except exc.SQLAlchemyError as e: |
| 88 | + raise Exception(f"SQLAlchemyError: {e}") |
| 89 | + finally: |
| 90 | + session.close() |
| 91 | + |
| 92 | + def close(self): |
| 93 | + """Close the database connection.""" |
| 94 | + self.engine.dispose() |
0 commit comments