21. MikroORM for Database Access
Status: Accepted Date: 2025-07-06
Context
The Mercury trading bot requires a robust and reliable way to interact with its PostgreSQL database for persisting state, storing trading data, and managing user information. Writing raw SQL queries is error-prone, hard to maintain, and does not leverage the power of TypeScript's type system. An Object-Relational Mapper (ORM) is needed to abstract database interactions and provide a type-safe API.
Decision
We will use MikroORM as the primary ORM for all PostgreSQL database operations within the Mercury bot and other backend services. MikroORM is a TypeScript-first ORM that uses the Data Mapper pattern, which helps keep our entity objects clean from database logic. Its key features—strong typing, automated schema migrations, and the Identity Map pattern for performance—make it an excellent choice for a data-intensive, type-safe application.
Consequences
Positive:
- Type Safety: MikroORM's design provides excellent type safety for queries and entities, reducing the risk of runtime errors.
- Clean Entities: The Data Mapper pattern keeps entity objects (our domain model) separate from the database persistence logic, leading to a cleaner architecture.
- Powerful Migrations: Its schema generator and migration tools simplify database schema management and evolution.
- Performance: The built-in Identity Map helps prevent redundant database queries for the same entity within a single transaction, improving performance.
Negative:
- Learning Curve: MikroORM has its own concepts (e.g.,
EntityManager,Unit of Work) and a specific way of handling relations that developers need to learn. - Configuration: Setting up MikroORM, especially its discovery paths for entities and migrations, can be more complex than with some other ORMs.
- Verbosity: The Data Mapper pattern can sometimes be more verbose than the Active Record pattern used by other ORMs like TypeORM.
Mitigation:
- Centralized Repositories: Encapsulate all database logic for a given entity within a dedicated repository module. This abstracts away the complexities of MikroORM's
EntityManagerfrom the rest of the application. - Clear Documentation & Examples: Maintain clear internal documentation and code examples demonstrating common database operations and patterns using MikroORM.
- Standardized Configuration: Develop a standardized MikroORM configuration that can be reused across all backend projects to ensure consistency and simplify setup.