82 lines
2.3 KiB
Markdown
82 lines
2.3 KiB
Markdown
# Database API Documentation
|
|
|
|
## Overview
|
|
The database module provides database connection management and basic operations for both PostgreSQL and SQLite databases. Key features include:
|
|
- Connection pooling for PostgreSQL
|
|
- Context managers for safe connection handling
|
|
- Unified interface for both database types
|
|
- SQL execution helpers
|
|
|
|
## Connection Management
|
|
|
|
### `get_db_connection(db_type='postgres')`
|
|
Context manager for database connections.
|
|
|
|
**Parameters:**
|
|
- `db_type`: 'postgres' or 'sqlite' (default: 'postgres')
|
|
|
|
**Usage:**
|
|
```python
|
|
with get_db_connection() as conn:
|
|
# Use connection
|
|
```
|
|
|
|
### `get_db_cursor(cursor_factory=None, db_type='postgres')`
|
|
Context manager for database cursors with automatic commit/rollback.
|
|
|
|
**Parameters:**
|
|
- `cursor_factory`: Optional cursor factory (e.g., psycopg2.extras.DictCursor)
|
|
- `db_type`: 'postgres' or 'sqlite' (default: 'postgres')
|
|
|
|
**Usage:**
|
|
```python
|
|
with get_db_cursor() as cursor:
|
|
cursor.execute("SELECT * FROM table")
|
|
```
|
|
|
|
## SQL Execution Helpers
|
|
|
|
### `execute_query(query, params=None, cursor_factory=None, fetch_one=False, db_type='postgres')`
|
|
Executes a query and returns results.
|
|
|
|
**Parameters:**
|
|
- `query`: SQL query string
|
|
- `params`: Query parameters (tuple/dict)
|
|
- `cursor_factory`: Optional cursor factory
|
|
- `fetch_one`: Return single row if True
|
|
- `db_type`: Database type
|
|
|
|
**Returns:**
|
|
- Query results (list or single row)
|
|
|
|
### `execute_update(query, params=None, db_type='postgres')`
|
|
Executes an update/insert/delete query.
|
|
|
|
**Parameters:**
|
|
- `query`: SQL query string
|
|
- `params`: Query parameters (tuple/dict)
|
|
- `db_type`: Database type
|
|
|
|
**Returns:**
|
|
- Number of affected rows
|
|
|
|
## Initialization
|
|
|
|
### `init_sqlite_db()`
|
|
Initializes SQLite database tables (api_endpoints, api_logs, api_users, api_operations).
|
|
|
|
## Configuration
|
|
Module uses configuration from:
|
|
- `DB_CONFIG` for PostgreSQL
|
|
- `SQLITE_CONFIG` for SQLite
|
|
|
|
## Error Handling
|
|
- All database operations are wrapped in try/except blocks
|
|
- Errors are logged with detailed context
|
|
- Connections are automatically returned to pool (PostgreSQL) or closed (SQLite)
|
|
|
|
## Best Practices
|
|
- Always use context managers (`with` statements) for connections/cursors
|
|
- For PostgreSQL, prefer connection pooling for better performance
|
|
- For complex transactions, use explicit commit/rollback
|