Skip to content

refactor: Refactor PositionDBConnector deep inheritance to composition #75

@YaronZaki

Description

@YaronZaki

Problem Statement

PositionDBConnector → UserDBConnector → DBConnector forms a three-level deep inheritance chain. This is a fragile "diamond" pattern: PositionDBConnector inherits from UserDBConnector which inherits from DBConnector, but both PositionDBConnector and DBConnector create their own engine instances.

Evidence

# quantara/web_app/db/crud/position.py:22
class PositionDBConnector(UserDBConnector):  # inherits UserDBConnector

# quantara/web_app/db/crud/user.py:17
class UserDBConnector(DBConnector):  # inherits DBConnector

# quantara/web_app/db/crud/base.py:19
class DBConnector:
    def __init__(self, db_url: str = SQLALCHEMY_DATABASE_URL):
        self.engine = create_engine(db_url)  # Creates its own engine!

database.py:24 already creates the engine — then DBConnector creates another one.

Impact

Medium — maintainability and testing difficulty. Deep inheritance makes testing hard (cannot easily mock intermediate layers). Changes to DBConnector ripple through all descendants. Adding new operations requires understanding the full chain. Two engine instances create confusion about which pool is used.

Proposed Solution

Refactor to composition: PositionDBConnector takes a DBConnector instance via constructor injection. Same for UserDBConnector. Each class depends on DBConnector directly rather than inheriting — or better, use the FastAPI get_database() dependency for session management.

Acceptance Criteria

  • PositionDBConnector no longer inherits from UserDBConnector
  • UserDBConnector no longer inherits from DBConnector
  • Classes use composition: accept DBConnector (or session) via constructor
  • Single engine instance used (from database.py)
  • All existing tests pass without modification (or minimal fixture updates)

File Map

  • quantara/web_app/db/crud/position.py — refactor to composition
  • quantara/web_app/db/crud/user.py — refactor to composition
  • quantara/web_app/db/crud/base.py — simplify DBConnector
  • quantara/web_app/db/database.py — may need session factory export
  • quantara/web_app/tests/db/ — update all DB tests

Testing Strategy

  • Unit: Test each refactored class in isolation with mocked DBConnector
  • Integration: Run full test suite — verify all database operations still work

Security Considerations

No security impact. Purely structural refactoring.

Definition of Done

  • Code implemented and peer-reviewed
  • Tests written and passing
  • PR linked and merged

Labels: refactoring
Priority: Medium
Difficulty: Advanced
Estimated Effort: 3d

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions