class ConnectionConfig
A dataclass that stores and manages database connection configuration parameters for SQL Server connections, providing methods to load from config files and generate connection strings.
/tf/active/vicechatdev/full_smartstat/sql_query_generator.py
310 - 345
simple
Purpose
ConnectionConfig encapsulates all necessary parameters for establishing a SQL Server database connection. It provides a structured way to manage connection credentials and settings, supports loading configuration from external Python files, and can generate SQLAlchemy-compatible connection strings. This class is designed to centralize database connection configuration and make it easy to pass connection details throughout an application.
Source Code
class ConnectionConfig:
"""Database connection configuration"""
server: str
database: str
username: str
password: str
port: int = 1433
driver: str = "ODBC Driver 17 for SQL Server"
@classmethod
def from_config_file(cls, config_path: str) -> 'ConnectionConfig':
"""Load connection config from Python config file"""
try:
# Import the config file dynamically
import importlib.util
spec = importlib.util.spec_from_file_location("sql_config", config_path)
config_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config_module)
db_config = config_module.DATABASE_CONFIG
return cls(
server=db_config['server'],
database=db_config['database'],
username=db_config['username'],
password=db_config['password'],
port=db_config.get('port', 1433),
driver=db_config.get('driver', "ODBC Driver 17 for SQL Server")
)
except Exception as e:
logger.error(f"Error loading connection config from {config_path}: {str(e)}")
raise
def to_connection_string(self) -> str:
"""Generate SQLAlchemy connection string"""
from urllib.parse import quote_plus
return f"mssql+pyodbc://{self.username}:{quote_plus(self.password)}@{self.server}:{self.port}/{self.database}?driver={quote_plus(self.driver)}"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
server: The hostname or IP address of the SQL Server database server
database: The name of the database to connect to on the server
username: The username credential for database authentication
password: The password credential for database authentication
port: The port number on which SQL Server is listening (default: 1433, the standard SQL Server port)
driver: The ODBC driver name to use for the connection (default: 'ODBC Driver 17 for SQL Server')
Return Value
Instantiation returns a ConnectionConfig object containing all database connection parameters. The from_config_file() class method returns a new ConnectionConfig instance populated from a config file. The to_connection_string() method returns a string formatted as a SQLAlchemy connection URL suitable for creating database engines.
Class Interface
Methods
from_config_file(cls, config_path: str) -> ConnectionConfig
Purpose: Class method that dynamically loads a Python config file and creates a ConnectionConfig instance from the DATABASE_CONFIG dictionary defined in that file
Parameters:
config_path: String path to a Python file containing a DATABASE_CONFIG dictionary with connection parameters
Returns: A new ConnectionConfig instance populated with values from the config file
to_connection_string(self) -> str
Purpose: Generates a SQLAlchemy-compatible connection string in the format required for mssql+pyodbc connections, with proper URL encoding of special characters
Returns: A formatted connection string suitable for use with SQLAlchemy's create_engine() function
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
server |
str | The hostname or IP address of the SQL Server instance | instance |
database |
str | The name of the target database on the server | instance |
username |
str | The username for database authentication | instance |
password |
str | The password for database authentication | instance |
port |
int | The TCP port number for the SQL Server connection (default: 1433) | instance |
driver |
str | The ODBC driver name to use for the connection (default: 'ODBC Driver 17 for SQL Server') | instance |
Dependencies
urllib.parseimportlib.utillogging
Required Imports
from dataclasses import dataclass
from urllib.parse import quote_plus
import importlib.util
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from urllib.parse import quote_plus
Condition: only when calling to_connection_string() method
Required (conditional)import importlib.util
Condition: only when calling from_config_file() class method
Required (conditional)Usage Example
# Direct instantiation
config = ConnectionConfig(
server='localhost',
database='mydb',
username='admin',
password='secret123',
port=1433,
driver='ODBC Driver 17 for SQL Server'
)
# Load from config file
# config.py should contain:
# DATABASE_CONFIG = {
# 'server': 'localhost',
# 'database': 'mydb',
# 'username': 'admin',
# 'password': 'secret123'
# }
config = ConnectionConfig.from_config_file('config.py')
# Generate connection string for SQLAlchemy
connection_string = config.to_connection_string()
print(connection_string)
# Output: mssql+pyodbc://admin:secret123@localhost:1433/mydb?driver=ODBC+Driver+17+for+SQL+Server
# Use with SQLAlchemy
from sqlalchemy import create_engine
engine = create_engine(connection_string)
Best Practices
- Always use from_config_file() to load credentials from external files rather than hardcoding them in source code
- Store config files outside version control and use environment-specific configurations
- The password is URL-encoded automatically in to_connection_string() to handle special characters safely
- Ensure the specified ODBC driver is installed on the target system before attempting connections
- Handle exceptions when calling from_config_file() as it will raise errors if the config file is malformed or missing required keys
- The class is immutable after instantiation (dataclass without frozen=True, but no setters provided)
- Use appropriate file permissions on config files containing passwords to prevent unauthorized access
- The logger must be defined in the module scope before using from_config_file() method
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_connection_config 66.9% similar
-
function get_default_connection_config 66.7% similar
-
class DataSource 62.4% similar
-
class DataSource_v2 60.4% similar
-
class Config 59.8% similar