| doc_id | DBS-ARCH-002 |
|---|---|
| doc_title | Database System Architecture |
| doc_version | 1.0.0 |
| doc_date | 2026-04-04 |
| doc_status | Released |
| project | database_system |
| category | ARCH |
SSOT: This document is the single source of truth for Database System Architecture.
Language: English | νκ΅μ΄
See also: advanced/ARCHITECTURE.md β implementation-detail companion (deferred).
- Overview
- Architecture Layers
- Core Components
- Design Principles
- Thread Safety
- Common System Result Integration
- Interop with Other Modules
- Error Handling
- Performance Characteristics
- Scalability
- Monitoring and Observability
- Future Extensions
- Dependencies
- Build Configuration
This document describes the architecture and design patterns of the Database System Phase 4 implementation.
Cross-reference: API Reference β Database backend, query builder, and ORM APIs Benchmarks β Connection pool and query performance data Backends Guide β PostgreSQL, SQLite, MongoDB, and Redis backend details Adapter Patterns β Backend-agnostic adapter implementations
Ecosystem reference: common_system API β Result<T> and IExecutor interfaces thread_system Architecture β Thread pool for async database operations container_system API β Data serialization for database records monitoring_system Architecture β Performance monitoring integration
The Database System is designed as a modular, enterprise-grade database abstraction layer that provides unified access to multiple database backends with advanced features for production environments.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Application Layer β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β ORM Framework β Security Layer β Async Operations β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Performance Monitoring β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Query Builders β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Connection Pooling β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Database Manager β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Database Backends β
β PostgreSQL β SQLite β MongoDB β Redis β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The abstract base class that defines the common interface for all database backends.
class database_base {
public:
virtual database_types database_type() = 0;
virtual bool connect(const std::string& connect_string) = 0;
virtual bool execute_query(const std::string& query_string) = 0;
virtual database_result select_query(const std::string& query_string) = 0;
// ... other virtual methods
};Design Patterns Used:
- Strategy Pattern: Each database backend implements the same interface
- Template Method Pattern: Common operations defined in base class
- RAII: Automatic resource management for connections
postgres_manager: PostgreSQL backend using libpqxxsqlite_manager: SQLite backend using sqlite3mongodb_manager: MongoDB backend using mongocxxredis_manager: Redis backend using hiredis
Singleton manager that handles database connections and mode switching.
class database_manager {
public:
static database_manager& handle();
bool set_mode(database_types db_type);
bool connect(const std::string& connection_string);
// ... database operations
};Design Patterns Used:
- Singleton Pattern: Global access point
- Factory Pattern: Creates appropriate database backends
- Command Pattern: Encapsulates database operations
Enterprise-grade connection pooling with adaptive sizing and monitoring.
class connection_pool {
private:
std::queue<std::unique_ptr<database_base>> available_connections_;
std::vector<std::unique_ptr<database_base>> active_connections_;
mutable std::mutex pool_mutex_;
std::condition_variable pool_condition_;
};Features:
- Dynamic connection creation/destruction
- Connection health monitoring
- Thread-safe operations
- Configurable pool sizes
- Connection timeout handling
Architecture:
Entity Definition β Metadata Generation β Schema Management β Query Execution
Key Components:
entity_base: Base class for all ORM entitiesfield_metadata: Type information and constraints for entity fieldsentity_metadata: Complete table schema informationquery_builder<Entity>: Type-safe query constructionentity_manager: Schema synchronization and entity lifecycle
C++20 Features Used:
- Concepts: Type-safe entity definitions
- Template Metaprogramming: Compile-time schema validation
- SFINAE: Type trait-based field detection
template<typename T>
concept Entity = requires(T t) {
typename T::primary_key_type;
{ t.table_name() } -> std::convertible_to<std::string>;
{ t.get_metadata() } -> std::same_as<const entity_metadata&>;
};Architecture:
Metrics Collection β Aggregation β Alerting β Export (Prometheus)
Components:
performance_monitor: Core metrics collection and analysisconnection_metrics: Connection pool utilization trackingquery_metrics: Query performance statisticsperformance_alert: Configurable alerting system
Thread Safety:
- Atomic counters for high-frequency metrics
- Mutex protection for complex data structures
- Lock-free data structures where possible
Multi-layered Security:
Application β Authentication β Authorization β Audit β Encryption
Components:
credential_manager: Secure credential storage with encryptionaccess_control: Role-based access control (RBAC)audit_logger: Comprehensive security event loggingsecurity_monitor: Real-time threat detectionquery_security: SQL injection prevention
Security Features:
- Master key encryption for credentials
- Session management with timeout
- Audit trail with tamper detection
- Threat pattern recognition
Async Architecture:
std::future β C++20 Coroutines β Stream Processing
Components:
async_executor: Thread pool for async operationsasync_database: Async wrapper for database operationsdatabase_awaitable: C++20 coroutine supportstream_processor: Real-time data streaming
Concurrency Patterns:
- Actor Model: Message-passing for async operations
- Future/Promise: Async result handling
- Coroutines: Modern async programming
- S: Single Responsibility - Each class has one reason to change
- O: Open/Closed - Extensible without modification
- L: Liskov Substitution - Interchangeable database backends
- I: Interface Segregation - Focused interfaces
- D: Dependency Inversion - Depend on abstractions
- RAII: Automatic resource management
- Smart Pointers: Memory safety
- Move Semantics: Performance optimization
- Constexpr: Compile-time computation
- Template Metaprogramming: Type safety
- Layered Architecture: Clear separation of concerns
- Plugin Architecture: Extensible database backends
- Event-Driven Architecture: Async operations and monitoring
- Microservices Ready: Lightweight DAL for service integration
- std::mutex: Protecting shared state
- std::atomic: Lock-free counters and flags
- std::condition_variable: Thread coordination
- std::shared_mutex: Reader-writer locks for read-heavy operations
- All database operations are thread-safe
- Connection pool supports concurrent access
- Performance monitoring uses atomic operations
- Compile-time optional integration with
common_systemResult types. - Define
DATABASE_USE_COMMON_SYSTEMto enablecommon::Result<T>/common::VoidResultwrappers:connect_result(const std::string&)disconnect_result()create_query_result(const std::string&)
- Benefits: exception-free error propagation, standardized error_info.
- With
container_system: use containers for typed serialization between app and DB layers when applicable. - Security audit logging is thread-safe
- No-throw: Performance-critical operations
- Strong: Transactional operations
- Basic: Resource cleanup guaranteed
// Database operations return status
bool success = db.execute_query("INSERT ...");
// Critical errors throw exceptions
try {
auto result = db.select_query("SELECT ...");
} catch (const database_exception& e) {
// Handle database-specific errors
}- O(1) connection acquisition/release
- Configurable pool sizing based on load
- Adaptive connection creation/destruction
- Prepared statements for SQL databases
- Connection reuse to minimize overhead
- Bulk operations for improved throughput
- Object pooling for frequently created objects
- Smart pointers for automatic cleanup
- Move semantics to minimize copying
- Multi-backend support with unified interface
- Connection pooling per database instance
- Async operations for non-blocking I/O
- Thread pool sizing based on hardware
- Lock-free data structures where possible
- Memory-efficient data structures
- Query execution times and counts
- Connection pool utilization
- Error rates and types
- Security events and threats
- Prometheus: Time-series metrics
- JSON: REST API endpoints
- Logs: Structured logging output
- GraphQL Support: Modern query interface
- Caching Layer: Redis-based query caching
- Schema Migrations: Automated database versioning
- Multi-tenant Support: Tenant isolation
- Custom Database Backends: Implement
database_base - Custom Security Providers: Implement security interfaces
- Custom Metrics Exporters: Extend monitoring system
- Custom Query Languages: Extend query builders
- C++20 Standard Library: Core functionality
- Database Client Libraries: Backend-specific (optional)
- OpenSSL: Encryption and TLS support
- libpqxx: PostgreSQL support
- sqlite3: SQLite support
- mongocxx: MongoDB support
- hiredis: Redis support
database_system sits at Tier 3 in the kcenon ecosystem, providing database abstraction.
graph TD
A[common_system] --> B[thread_system]
A --> C[container_system]
B --> D[logger_system]
B --> E[monitoring_system]
D --> F[database_system]
E --> F
F --> G[network_system]
G --> H[pacs_system]
style F fill:#f9f,stroke:#333,stroke-width:3px
Ecosystem reference: common_system β Tier 0: Result<T>, IExecutor thread_system β Tier 1: Async operations (optional) container_system β Tier 1: Data serialization (optional) monitoring_system β Tier 3: Performance monitoring (optional) network_system β Tier 4: Transport layer (consumer) pacs_system β Tier 5: DICOM database (consumer)
option(ENABLE_POSTGRESQL "Enable PostgreSQL support" ON)
option(ENABLE_SQLITE "Enable SQLite support" OFF)
option(ENABLE_MONGODB "Enable MongoDB support" OFF)
option(ENABLE_REDIS "Enable Redis support" OFF)- Header-only: Core components
- Optional linking: Database client libraries
- Mock implementations: Testing without databases
This architecture provides a solid foundation for database applications with modern C++ features, comprehensive security, and performance monitoring.
Last Updated: 2025-10-20