Skip to content

Add Database Connection URL Property to SqlAlchemyConfig #28

@Mohammadreza-kh94

Description

@Mohammadreza-kh94

Feature Description

Enhance SqlAlchemyConfig to automatically generate and store database connection URLs from individual connection parameters.

Problem Statement

Currently, developers must manually construct database connection URLs throughout the codebase using individual parameters:

db_url = f"postgresql://{sqlalchemy_config.USERNAME}:{sqlalchemy_config.PASSWORD}@{sqlalchemy_config.HOST}:{sqlalchemy_config.PORT}/{sqlalchemy_config.DATABASE}"

This leads to code duplication, potential inconsistencies, and requires extra boilerplate code whenever database connections are needed.

Proposed Solution

Add a DB_URL field to SqlAlchemyConfig that is automatically populated during model initialization if all required connection parameters are present. This approach uses Pydantic's model_validator to ensure the URL is correctly generated whenever the model is instantiated.

Use Cases

  1. When creating database connections in various parts of the application
  2. When initializing ORM adapters that require connection strings
  3. When spinning up database-dependent services in testing environments
  4. When configuring database migrations and schema management tools

Implementation Ideas

The implementation adds:

  1. A new DB_URL field that will store the connection string
  2. A Pydantic model_validator that automatically builds the connection URL if:
    • DB_URL is not explicitly provided
    • All required connection parameters (username, host, port, database) are present
@model_validator(mode='after')
def build_connection_url(self) -> "SqlAlchemyConfig":
    """Build and populate DB_URL if not provided but all required connection parameters are present."""
    if self.DB_URL is not None:
        return self
        
    if all([self.USERNAME, self.HOST, self.PORT, self.DATABASE]):
        password_part = f":{self.PASSWORD}" if self.PASSWORD else ""
        self.DB_URL = f"{self.DRIVER_NAME}://{self.USERNAME}{password_part}@{self.HOST}:{self.PORT}/{self.DATABASE}"
        
    return self

Benefits

  • Reduces code duplication
  • Ensures consistent URL format across the application
  • Simplifies code that needs database connections
  • Leverages Pydantic's validation system rather than custom properties
  • Maintains backward compatibility

Would you be willing to help implement this feature?

  • Yes, I'd be interested in contributing code
  • Yes, I'd be interested in testing
  • Yes, I'd be interested in documenting

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions