Database & Repository Pattern
Relevant source files
The following files were used as context for generating this wiki page:
Polar utilizes a structured Database and Repository pattern to manage data persistence and business logic separation. The system is built on PostgreSQL using SQLAlchemy as the Object-Relational Mapper (ORM), with a strict modular architecture that encapsulates database queries within dedicated repository classes.
The architecture ensures that business logic (Service Layer) remains decoupled from the specifics of database interactions (Repository Layer). All database operations are performed asynchronously using Python's asyncio and SQLAlchemy's AsyncSession.
Sources: AGENTS.md, server/CLAUDE.md, DEVELOPMENT.md
Core Architecture
The backend follows a tiered architecture where the data flow is strictly defined. Requests move from API endpoints to services, which then utilize repositories to interact with the database models.
The diagram shows the standard flow of data where repositories act as the sole interface between the application's business logic and the database.
Sources: server/CLAUDE.md, DEVELOPMENT.md
Repository Pattern
In Polar, all database queries must be contained within repository files (repository.py) located inside their respective modules. Repositories inherit from RepositoryBase to provide a consistent set of CRUD and utility methods.
Key Repository Principles
- Encapsulation: No raw SQL or SQLAlchemy queries should exist in services or endpoints; they must be abstracted into the repository.
- Session Management: Repository instances are created using the
from_session(session)factory method. The session is maintained as an internal attribute (self.session) and should not be passed to individual methods. - Domain Objects: Methods prefer accepting and returning domain objects (e.g.,
Order) rather than just IDs. - Flush vs. Commit: The
flushparameter (defaulting toFalse) is used to control transaction boundaries within the session. Explicitsession.commit()is generally avoided in business logic as it is handled by the API or worker middleware.
Sources: AGENTS.md, server/CLAUDE.md
Base Repository Methods
The RepositoryBase provides standardized methods for common operations:
| Method | Description |
|---|---|
get_base_statement() | Returns a basic select(self.model) statement. |
get_one(statement) | Executes a query and returns one result; raises an exception if not found. |
get_one_or_none(statement) | Returns one result or None. Uses .unique() for safety with joined loads. |
get_all(statement) | Returns all matching results as a sequence. |
paginate(statement, limit, page) | Returns a tuple containing the results and the total count. |
create(object, flush=False) | Adds a new object to the database session. |
update(object, update_dict) | Updates fields on an existing object using a dictionary. |
Sources: server/CLAUDE.md
Model Structure
SQLAlchemy models are defined globally in server/polar/models/ and serve as the blueprint for the database schema. Most models inherit from a shared Model base that includes standard fields like id (UUID), created_at, and updated_at.
Standard Model Fields
| Field | Type | Description |
|---|---|---|
id | UUID | Primary key, automatically generated. |
created_at | Timestamp | Set automatically upon creation. |
updated_at | Timestamp | Updated automatically on every modification. |
deleted_at | Timestamp | Used for soft-deletion (via RepositorySoftDeletionMixin). |
Sources: server/polar/models/base.py, server/CLAUDE.md
Database Session Lifecycle
Polar utilizes FastAPI's dependency injection to manage database sessions. Sessions are categorized into read-only and write-enabled sessions to optimize performance and safety.
This sequence illustrates the lifecycle of a database session from injection at the endpoint to the automated commit at the end of the request cycle.
Sources: server/CLAUDE.md, AGENTS.md
Advanced Querying & Mixins
Repositories can be enhanced with Mixins to support common patterns:
RepositorySoftDeletionMixin: Provides logic for handling models withdeleted_atfields, ensuring queries exclude deleted items by default.RepositorySortingMixin: Standardizes how sorting parameters are applied to SQLAlchemy statements based on defined property enums.- Auth-Aware Statements: Repositories often implement
get_readable_statement(auth_subject)to automatically apply security filters (e.g., filtering byorganization_id) based on the current user's permissions.
Sources: server/CLAUDE.md
Subquery Standards
Subqueries in Polar must project explicit columns. Using select(Model).subquery() is discouraged because it re-materializes every mapped column, bypassing deferred loading. Developers are instructed to use .with_only_columns(...) to narrow the scope before calling .subquery().
Sources: server/CLAUDE.md
Summary
The Database & Repository pattern in Polar provides a robust framework for managing complex payment infrastructure data. By strictly separating query logic into Repositories and business logic into Services, the codebase maintains high maintainability and testability. The use of SQLAlchemy's asynchronous capabilities ensures the platform remains performant under load, while standardized Mixins provide consistent behavior for features like soft deletion and authorization-based filtering.