Database
Database connections and query execution for DesignSafe research databases.
Database Accessor
Provides lazy access to different DesignSafe database connections via properties.
This class manages multiple database connections and provides convenient property-based access to different DesignSafe databases. Each database connection is created only when first accessed (lazy initialization) and reused for subsequent calls.
The accessor supports the following databases through properties: - ngl: Natural hazards engineering research database - vp: Vulnerability and performance database - eq: Post-earthquake recovery database
ATTRIBUTE | DESCRIPTION |
---|---|
_connections |
Internal storage for database instances.
TYPE:
|
Example
accessor = DatabaseAccessor() DatabaseAccessor initialized. Connections will be created on first access.
Access NGL database (created on first access)
ngl_db = accessor.ngl First access to 'ngl', initializing DSDatabase... Successfully connected to database 'sjbrande_ngl_db' on 129.114.52.174.
Query the database
results = ngl_db.read_sql("SELECT COUNT(*) as total FROM users")
Close all connections when done
accessor.close_all() Closing all active database engines/pools... Closed 1 database engine(s).
Initialize the DatabaseAccessor with empty connection slots.
Creates a dictionary to hold database connections for each configured database, but does not establish any connections until they are first accessed.
Source code in dapi/db/accessor.py
ngl
property
Access the NGL (Natural Hazards Engineering) database connection manager.
Provides access to the sjbrande_ngl_db database containing natural hazards engineering research data. The connection is created on first access.
RETURNS | DESCRIPTION |
---|---|
DSDatabase
|
Connected database instance for the NGL database.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
Exception
|
If database connection fails during initialization. |
Example
ngl_db = accessor.ngl df = ngl_db.read_sql("SELECT * FROM earthquake_data LIMIT 10")
vp
property
Access the VP (Vulnerability and Performance) database connection manager.
Provides access to the sjbrande_vpdb database containing vulnerability and performance analysis data. The connection is created on first access.
RETURNS | DESCRIPTION |
---|---|
DSDatabase
|
Connected database instance for the VP database.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
Exception
|
If database connection fails during initialization. |
Example
vp_db = accessor.vp df = vp_db.read_sql("SELECT * FROM vulnerability_models LIMIT 10")
eq
property
Access the EQ (Post-Earthquake Recovery) database connection manager.
Provides access to the post_earthquake_recovery database containing post-earthquake recovery research data. The connection is created on first access.
RETURNS | DESCRIPTION |
---|---|
DSDatabase
|
Connected database instance for the EQ database.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
Exception
|
If database connection fails during initialization. |
Example
eq_db = accessor.eq df = eq_db.read_sql("SELECT * FROM recovery_metrics LIMIT 10")
close_all
Close all active database engines and their connection pools.
This method iterates through all database connections and properly closes their SQLAlchemy engines and connection pools. This should be called when the DatabaseAccessor is no longer needed to prevent connection leaks.
Note
After calling close_all(), accessing any database property will create new connections since the instances are reset to None.
Example
accessor = DatabaseAccessor() ngl_db = accessor.ngl # Creates connection vp_db = accessor.vp # Creates connection accessor.close_all() # Closes both connections Closing all active database engines/pools... Closing connection pool for database 'sjbrande_ngl_db'. Closing connection pool for database 'sjbrande_vpdb'. Closed 2 database engine(s).
Source code in dapi/db/accessor.py
Database Engine
Manages connection and querying for a specific DesignSafe database.
This class provides a high-level interface for connecting to preconfigured DesignSafe databases using SQLAlchemy with connection pooling. It supports environment-based configuration and provides query results in multiple formats.
ATTRIBUTE | DESCRIPTION |
---|---|
user |
Database username for authentication.
TYPE:
|
password |
Database password for authentication.
TYPE:
|
host |
Database host address.
TYPE:
|
port |
Database port number.
TYPE:
|
db |
Name of the connected database.
TYPE:
|
dbname_short |
Shorthand name for the database.
TYPE:
|
engine |
SQLAlchemy engine for database connections.
TYPE:
|
Session |
Session factory for database operations.
TYPE:
|
Example
db = DSDatabase("ngl") df = db.read_sql("SELECT COUNT(*) as total FROM users") print(df.iloc[0]['total']) db.close()
Initialize the DSDatabase instance and create the SQLAlchemy engine.
Sets up database connection parameters from environment variables or defaults, creates a SQLAlchemy engine with connection pooling, and prepares the session factory.
PARAMETER | DESCRIPTION |
---|---|
dbname
|
Shorthand name for the database to connect to. Must be a key in db_config. Defaults to "ngl". Available options: "ngl", "vp", "eq".
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If dbname is not a valid configured database name. |
SQLAlchemyError
|
If database engine creation or connection fails. |
Example
db = DSDatabase("ngl") # Connect to NGL database db = DSDatabase("vp") # Connect to VP database
Source code in dapi/db/db.py
engine
instance-attribute
engine = create_engine(
f"mysql+pymysql://{user}:{password}@{host}:{port}/{db}",
pool_recycle=3600,
pool_pre_ping=True,
)
read_sql
Execute a SQL query using a dedicated session and return the results.
This method obtains a session from the connection pool, executes the provided SQL query, and returns results in the specified format. The session is automatically closed after execution, returning the connection to the pool.
PARAMETER | DESCRIPTION |
---|---|
sql
|
The SQL query string to execute. Can be any valid SQL statement including SELECT, INSERT, UPDATE, DELETE, etc.
TYPE:
|
output_type
|
Format for query results. Must be either 'DataFrame' for pandas.DataFrame or 'dict' for list of dictionaries. Defaults to "DataFrame".
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
pandas.DataFrame or List[Dict]: Query results in the requested format. - 'DataFrame': Returns a pandas DataFrame with column names as headers - 'dict': Returns a list of dictionaries where each dict represents a row |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If sql is empty/None or output_type is not 'DataFrame' or 'dict'. |
SQLAlchemyError
|
If database error occurs during query execution. |
Exception
|
If unexpected errors occur during query processing. |
Example
Get DataFrame result
df = db.read_sql("SELECT name, age FROM users WHERE age > 25") print(df.columns.tolist()) # ['name', 'age']
Get dictionary result
results = db.read_sql("SELECT COUNT(*) as total FROM users", output_type="dict") print(results[0]['total']) # 150
Source code in dapi/db/db.py
close
Dispose of the SQLAlchemy engine and close all database connections.
This method properly shuts down the database engine and its connection pool. It should be called when the database instance is no longer needed to prevent connection leaks and free up database resources.
Note
After calling close(), this DSDatabase instance should not be used for further database operations as the engine will be disposed.
Example
db = DSDatabase("ngl")
... perform database operations ...
db.close() Disposing engine and closing pool for 'ngl'... Engine for 'ngl' disposed.
Source code in dapi/db/db.py
Database Configuration
dict: Database configuration mapping.
Maps shorthand database names to their configuration details.
Keys
- "ngl": Natural hazards engineering research database
- "vp": Vulnerability and performance database
- "eq": Post-earthquake recovery database
Each value contains
- "dbname" (str): Actual database name in the MySQL server
- "env_prefix" (str): Prefix for environment variables containing credentials
Environment Variable Pattern
For each database, the following environment variables are checked: - {env_prefix}DB_USER: Database username (default: "dspublic") - {env_prefix}DB_PASSWORD: Database password (default: "R3ad0nlY") - {env_prefix}DB_HOST: Database host (default: "129.114.52.174") - {env_prefix}DB_PORT: Database port (default: 3306)