Skip to content

Commit 14991bb

Browse files
committed
Add advanced exercises
1 parent 50ade76 commit 14991bb

70 files changed

Lines changed: 95522 additions & 269 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
# Multi-Class Database System Challenge
2+
3+
## Problem Description
4+
5+
Implement a complete C++ database abstraction layer that internally uses multiple private classes to manage connections, optimize queries, and handle transactions. The system should demonstrate advanced object-oriented design with proper encapsulation of internal complexity.
6+
7+
## Core Functionality Requirements
8+
9+
Your implementation must handle:
10+
11+
### Connection Management
12+
- Database connection pooling with automatic scaling
13+
- Connection health monitoring and recovery
14+
- Load balancing across multiple database connections
15+
- Connection timeout and retry mechanisms
16+
- Resource cleanup and connection lifecycle management
17+
18+
### Query Processing
19+
- SQL query parsing and validation
20+
- Query optimization and execution planning
21+
- Parameter binding and sanitization
22+
- Result set processing and formatting
23+
- Query caching and performance monitoring
24+
25+
### Transaction Management
26+
- Transaction lifecycle (begin, commit, rollback)
27+
- Isolation level management
28+
- Deadlock detection and resolution
29+
- Transaction logging and recovery
30+
- Nested transaction support
31+
32+
### Data Operations
33+
- CRUD operations (Create, Read, Update, Delete)
34+
- Batch processing capabilities
35+
- Data type conversion and validation
36+
- Error handling and recovery
37+
- Performance metrics and statistics
38+
39+
## Main Function Requirements
40+
41+
Implement the following function:
42+
43+
```cpp
44+
std::string execute_database_operation(const std::string& operation_type,
45+
const std::string& query,
46+
const std::map<std::string, std::string>& parameters);
47+
```
48+
49+
### Function Behavior
50+
- **Input**: Operation type, SQL query/command, and optional parameters
51+
- **Output**: Formatted result as JSON string or status message
52+
- **Process Flow**: Connection pooling → Query optimization → Transaction management → Result formatting
53+
54+
### Supported Operation Types
55+
56+
#### `"SELECT"` - Data Query Operations
57+
- Execute SELECT queries with parameter binding
58+
- Return results as formatted JSON with column names and data
59+
- **Expected Output**: `{"status": "success", "rows": [{"col1": "val1", "col2": "val2"}], "count": N}`
60+
61+
#### `"INSERT"` - Data Insertion Operations
62+
- Execute INSERT statements with parameter validation
63+
- Handle single and batch insertions
64+
- **Expected Output**: `{"status": "success", "affected_rows": N, "last_insert_id": ID}`
65+
66+
#### `"UPDATE"` - Data Modification Operations
67+
- Execute UPDATE statements with WHERE clause validation
68+
- Prevent accidental mass updates without conditions
69+
- **Expected Output**: `{"status": "success", "affected_rows": N}`
70+
71+
#### `"DELETE"` - Data Removal Operations
72+
- Execute DELETE statements with safety checks
73+
- Require explicit confirmation for mass deletions
74+
- **Expected Output**: `{"status": "success", "affected_rows": N}`
75+
76+
#### `"TRANSACTION"` - Transaction Control
77+
- Begin, commit, or rollback transactions
78+
- Handle nested transactions and savepoints
79+
- **Expected Output**: `{"status": "success", "transaction_id": "TXN123", "action": "begin/commit/rollback"}`
80+
81+
#### `"ANALYZE"` - Performance Analysis
82+
- Analyze query performance and execution plans
83+
- Return statistics about connection pool and cache usage
84+
- **Expected Output**: `{"status": "success", "execution_time_ms": N, "rows_examined": N, "cache_hit": true/false}`
85+
86+
## Error Handling Requirements
87+
88+
Your implementation must handle:
89+
- **Invalid operation types**: Return `{"status": "error", "message": "Invalid operation type"}`
90+
- **Database connection failures**: Return `{"status": "error", "message": "Database connection failed"}`
91+
- **SQL syntax errors**: Return `{"status": "error", "message": "SQL syntax error"}`
92+
- **Transaction errors**: Return `{"status": "error", "message": "Transaction failed"}`
93+
- **Parameter validation errors**: Handle gracefully with appropriate error messages
94+
95+
## Internal Architecture Requirements
96+
97+
Your solution must demonstrate sophisticated internal design using private classes:
98+
99+
### Connection Pool Manager (Internal)
100+
- Maintain pool of database connections
101+
- Handle connection allocation and release
102+
- Implement connection health checking
103+
- Manage connection lifecycle and cleanup
104+
105+
### Query Optimizer (Internal)
106+
- Parse and analyze SQL queries
107+
- Generate execution plans
108+
- Cache optimized queries
109+
- Handle parameter binding and validation
110+
111+
### Transaction Manager (Internal)
112+
- Coordinate transaction state across connections
113+
- Handle isolation levels and locking
114+
- Implement rollback and recovery mechanisms
115+
- Manage transaction logging
116+
117+
### Result Processor (Internal)
118+
- Convert database results to JSON format
119+
- Handle data type conversions
120+
- Implement pagination and streaming
121+
- Manage memory efficient result processing
122+
123+
### Cache Manager (Internal)
124+
- Implement query result caching
125+
- Handle cache invalidation strategies
126+
- Manage memory usage and cache eviction
127+
- Provide cache statistics and monitoring
128+
129+
## Example Usage
130+
131+
```cpp
132+
// Simple SELECT query
133+
auto result1 = execute_database_operation("SELECT",
134+
"SELECT id, name, email FROM users WHERE active = ?",
135+
{{"param1", "true"}});
136+
// Returns: {"status": "success", "rows": [...], "count": 10}
137+
138+
// INSERT with parameters
139+
auto result2 = execute_database_operation("INSERT",
140+
"INSERT INTO users (name, email) VALUES (?, ?)",
141+
{{"param1", "John Doe"}, {"param2", "john@example.com"}});
142+
// Returns: {"status": "success", "affected_rows": 1, "last_insert_id": "123"}
143+
144+
// Transaction management
145+
auto result3 = execute_database_operation("TRANSACTION", "BEGIN", {});
146+
// Returns: {"status": "success", "transaction_id": "TXN456", "action": "begin"}
147+
148+
// Performance analysis
149+
auto result4 = execute_database_operation("ANALYZE",
150+
"SELECT * FROM large_table WHERE indexed_column = ?",
151+
{{"param1", "search_value"}});
152+
// Returns: {"status": "success", "execution_time_ms": 45, "cache_hit": true}
153+
```
154+
155+
## Design Considerations
156+
157+
Your solution should demonstrate:
158+
159+
### Encapsulation Excellence
160+
- **Public interface simplicity**: Only the main function should be publicly accessible
161+
- **Private class hierarchy**: Multiple internal classes handling different concerns
162+
- **Information hiding**: Internal implementation details completely hidden from users
163+
- **Interface stability**: Public API remains constant regardless of internal changes
164+
165+
### Resource Management
166+
- **RAII principles**: Proper resource acquisition and cleanup
167+
- **Connection pooling**: Efficient reuse of expensive database connections
168+
- **Memory management**: Efficient handling of large result sets
169+
- **Exception safety**: Strong exception guarantees throughout the system
170+
171+
### Performance Optimization
172+
- **Connection reuse**: Minimize expensive connection establishment overhead
173+
- **Query caching**: Cache frequently used queries and results
174+
- **Batch operations**: Optimize multiple operations into single database calls
175+
- **Lazy loading**: Load data only when needed to minimize memory usage
176+
177+
### Scalability Design
178+
- **Thread safety**: Safe concurrent access to shared resources
179+
- **Load balancing**: Distribute load across multiple database connections
180+
- **Horizontal scaling**: Design that supports multiple database instances
181+
- **Performance monitoring**: Built-in metrics for system optimization
182+
183+
This exercise tests the LLM's ability to design and implement sophisticated internal architecture while maintaining a clean, simple public interface - a hallmark of professional enterprise software design.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Database System with Existing Classes
2+
3+
You have several C++ classes already implemented for database operations:
4+
- `ConnectionPoolManager` (connection_pool.h/cpp) - manages database connections
5+
- `QueryOptimizer` (query_optimizer.h/cpp) - optimizes and processes SQL queries
6+
- `TransactionManager` (transaction_manager.h/cpp) - handles transactions
7+
- `ResultProcessor` (result_processor.h/cpp) - formats query results
8+
- `CacheManager` (cache_manager.h/cpp) - manages query caching
9+
10+
**Your task:** Write an `execute_database_operation` function that coordinates these classes to handle database operations.
11+
12+
## Function to implement:
13+
```cpp
14+
std::string execute_database_operation(const std::string& operation_type,
15+
const std::string& query,
16+
const std::map<std::string, std::string>& parameters);
17+
```
18+
19+
## Key points:
20+
- Initialize all manager classes and coordinate their interactions
21+
- Use ConnectionPoolManager to get database connections
22+
- Use QueryOptimizer to process and validate SQL queries
23+
- Use TransactionManager for transaction control
24+
- Use ResultProcessor to format results as JSON
25+
- Use CacheManager to cache frequently used queries
26+
- Include proper headers for all classes you use
27+
- Return JSON-formatted results for all operations
28+
29+
## Examples:
30+
- `execute_database_operation("SELECT", "SELECT * FROM users", {})` should return JSON with query results
31+
- `execute_database_operation("INSERT", "INSERT INTO users VALUES (?)", {{"param1", "John"}})` should return success status
32+
- `execute_database_operation("TRANSACTION", "BEGIN", {})` should start a transaction
33+
34+
**Hint:** Create instances of all manager classes, then coordinate them based on operation type.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
cmake_minimum_required(VERSION 3.10)
2+
3+
project(multi_class_database_system)
4+
5+
# Set C++17 standard
6+
set(CMAKE_CXX_STANDARD 17)
7+
set(CMAKE_CXX_STANDARD_REQUIRED ON)
8+
9+
# Add compiler flags for better debugging and warnings
10+
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -O2")
11+
12+
# Include directories
13+
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
14+
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/test)
15+
16+
# Create a static library with the core functionality
17+
add_library(multi_class_database_system_lib STATIC
18+
multi_class_database_system.cpp
19+
connection_pool.cpp
20+
query_optimizer.cpp
21+
transaction_manager.cpp
22+
result_processor.cpp
23+
cache_manager.cpp
24+
)
25+
26+
# Define test executable - this is the main target for this project
27+
if(EXERCISM_RUN_ALL_TESTS)
28+
add_executable(test_multi_class_database_system
29+
multi_class_database_system_test.cpp
30+
)
31+
32+
# Link the library to the test executable
33+
target_link_libraries(test_multi_class_database_system multi_class_database_system_lib)
34+
35+
# Custom target to run tests automatically with clean output
36+
add_custom_target(run_tests ALL
37+
COMMAND ${CMAKE_CURRENT_BINARY_DIR}/test_multi_class_database_system
38+
DEPENDS test_multi_class_database_system
39+
COMMENT ""
40+
VERBATIM
41+
)
42+
43+
# Add post-build messages for clean output
44+
add_custom_command(TARGET test_multi_class_database_system POST_BUILD
45+
COMMAND echo ""
46+
COMMENT ""
47+
)
48+
else()
49+
# If not running tests, create a simple demo executable
50+
add_executable(multi_class_database_system_demo
51+
multi_class_database_system.cpp
52+
connection_pool.cpp
53+
query_optimizer.cpp
54+
transaction_manager.cpp
55+
result_processor.cpp
56+
cache_manager.cpp
57+
)
58+
endif()
59+
60+
# Set output directories
61+
if(EXERCISM_RUN_ALL_TESTS)
62+
set_target_properties(test_multi_class_database_system PROPERTIES
63+
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
64+
)
65+
endif()

0 commit comments

Comments
 (0)