|
| 1 | +# Database Standards Quick Reference |
| 2 | + |
| 3 | +## ⚠️ CRITICAL RULES |
| 4 | + |
| 5 | +1. **PyDAL MANDATORY for ALL runtime operations** - no exceptions |
| 6 | +2. **SQLAlchemy + Alembic for schema/migrations only** - never for runtime queries |
| 7 | +3. **Support ALL databases by default**: PostgreSQL, MySQL, MariaDB Galera, SQLite |
| 8 | +4. **DB_TYPE environment variable required** - maps to connection string prefix |
| 9 | +5. **Connection pooling REQUIRED** - use PyDAL built-in pool_size configuration |
| 10 | +6. **Thread-safe connections MANDATORY** - thread-local storage for multi-threaded apps |
| 11 | +7. **Retry logic with exponential backoff** - handle database initialization delays |
| 12 | +8. **MariaDB Galera special handling** - WSREP checks, short transactions, charset utf8mb4 |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +## Database Support Matrix |
| 17 | + |
| 18 | +| Database | DB_TYPE | Version | Default Port | Use Case | |
| 19 | +|----------|---------|---------|--------------|----------| |
| 20 | +| PostgreSQL | `postgresql` | **16.x** | 5432 | Production (primary) | |
| 21 | +| MySQL | `mysql` | 8.0+ | 3306 | Production alternative | |
| 22 | +| MariaDB Galera | `mysql` | 10.11+ | 3306 | HA clusters (special config) | |
| 23 | +| SQLite | `sqlite` | 3.x | N/A | Development/lightweight | |
| 24 | + |
| 25 | +--- |
| 26 | + |
| 27 | +## Dual-Library Architecture (Python) |
| 28 | + |
| 29 | +### SQLAlchemy + Alembic |
| 30 | +- **Purpose**: Schema definition and version-controlled migrations ONLY |
| 31 | +- **When**: Application first-time setup |
| 32 | +- **What**: Define tables, columns, relationships |
| 33 | +- **Not for**: Runtime queries, data operations |
| 34 | + |
| 35 | +### PyDAL |
| 36 | +- **Purpose**: ALL runtime database operations |
| 37 | +- **When**: Every request, transaction, query |
| 38 | +- **What**: Queries, inserts, updates, deletes, transactions |
| 39 | +- **Built-in**: Connection pooling, thread safety, retry logic |
| 40 | + |
| 41 | +--- |
| 42 | + |
| 43 | +## Environment Variables |
| 44 | + |
| 45 | +```bash |
| 46 | +DB_TYPE=postgresql # Database type |
| 47 | +DB_HOST=localhost # Database host |
| 48 | +DB_PORT=5432 # Database port |
| 49 | +DB_NAME=app_db # Database name |
| 50 | +DB_USER=app_user # Database username |
| 51 | +DB_PASS=app_pass # Database password |
| 52 | +DB_POOL_SIZE=10 # Connection pool size (default: 10) |
| 53 | +DB_MAX_RETRIES=5 # Maximum connection retries (default: 5) |
| 54 | +DB_RETRY_DELAY=5 # Retry delay in seconds (default: 5) |
| 55 | +``` |
| 56 | + |
| 57 | +--- |
| 58 | + |
| 59 | +## PyDAL Connection Pattern |
| 60 | + |
| 61 | +```python |
| 62 | +from pydal import DAL |
| 63 | + |
| 64 | +def get_db(): |
| 65 | + db_type = os.getenv('DB_TYPE', 'postgresql') |
| 66 | + db_uri = f"{db_type}://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}" |
| 67 | + |
| 68 | + db = DAL( |
| 69 | + db_uri, |
| 70 | + pool_size=int(os.getenv('DB_POOL_SIZE', '10')), |
| 71 | + migrate=True, |
| 72 | + check_reserved=['all'], |
| 73 | + lazy_tables=True |
| 74 | + ) |
| 75 | + return db |
| 76 | +``` |
| 77 | + |
| 78 | +--- |
| 79 | + |
| 80 | +## Thread-Safe Usage Pattern |
| 81 | + |
| 82 | +**NEVER share DAL instance across threads. Use thread-local storage:** |
| 83 | + |
| 84 | +```python |
| 85 | +import threading |
| 86 | + |
| 87 | +thread_local = threading.local() |
| 88 | + |
| 89 | +def get_thread_db(): |
| 90 | + if not hasattr(thread_local, 'db'): |
| 91 | + thread_local.db = DAL(db_uri, pool_size=10, migrate=False) |
| 92 | + return thread_local.db |
| 93 | +``` |
| 94 | + |
| 95 | +**Flask pattern (automatic via g context):** |
| 96 | + |
| 97 | +```python |
| 98 | +from flask import g |
| 99 | + |
| 100 | +def get_db(): |
| 101 | + if 'db' not in g: |
| 102 | + g.db = DAL(db_uri, pool_size=10) |
| 103 | + return g.db |
| 104 | + |
| 105 | +@app.teardown_appcontext |
| 106 | +def close_db(error): |
| 107 | + db = g.pop('db', None) |
| 108 | + if db: db.close() |
| 109 | +``` |
| 110 | + |
| 111 | +--- |
| 112 | + |
| 113 | +## MariaDB Galera Special Requirements |
| 114 | + |
| 115 | +1. **Connection String**: Use `mysql://` (same as MySQL) |
| 116 | +2. **Driver Args**: Set charset to utf8mb4 |
| 117 | +3. **WSREP Checks**: Verify `wsrep_ready` before critical writes |
| 118 | +4. **Auto-Increment**: Configure `innodb_autoinc_lock_mode=2` for interleaved mode |
| 119 | +5. **Transactions**: Keep short to avoid certification conflicts |
| 120 | +6. **DDL Operations**: Plan during low-traffic periods (uses Total Order Isolation) |
| 121 | + |
| 122 | +```python |
| 123 | +# Galera-specific configuration |
| 124 | +db = DAL( |
| 125 | + f"mysql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}", |
| 126 | + pool_size=10, |
| 127 | + driver_args={'charset': 'utf8mb4'} |
| 128 | +) |
| 129 | +``` |
| 130 | + |
| 131 | +--- |
| 132 | + |
| 133 | +## Connection Pooling & Retry Logic |
| 134 | + |
| 135 | +```python |
| 136 | +import time |
| 137 | + |
| 138 | +def wait_for_database(max_retries=5, retry_delay=5): |
| 139 | + """Wait for DB with retry logic""" |
| 140 | + for attempt in range(max_retries): |
| 141 | + try: |
| 142 | + db = get_db() |
| 143 | + db.close() |
| 144 | + return True |
| 145 | + except Exception as e: |
| 146 | + print(f"Attempt {attempt+1}/{max_retries} failed: {e}") |
| 147 | + if attempt < max_retries - 1: |
| 148 | + time.sleep(retry_delay) |
| 149 | + return False |
| 150 | + |
| 151 | +# Application startup |
| 152 | +if not wait_for_database(): |
| 153 | + sys.exit(1) |
| 154 | +db = get_db() |
| 155 | +``` |
| 156 | + |
| 157 | +--- |
| 158 | + |
| 159 | +## Concurrency Selection |
| 160 | + |
| 161 | +| Workload | Approach | Libraries | Pool Size Formula | |
| 162 | +|----------|----------|-----------|-------------------| |
| 163 | +| I/O-bound (>100 concurrent) | Async | `asyncio`, `databases` | pool = concurrent / 2 | |
| 164 | +| CPU-bound | Multi-processing | `multiprocessing` | pool = CPU cores | |
| 165 | +| Mixed/Blocking I/O | Multi-threading | `threading`, `ThreadPoolExecutor` | pool = (2 × cores) + spindles | |
| 166 | + |
| 167 | +--- |
| 168 | + |
| 169 | +## Go Database Requirements |
| 170 | + |
| 171 | +When using Go for high-performance apps: |
| 172 | +- **GORM** (preferred): Full ORM with PostgreSQL/MySQL support |
| 173 | +- **sqlx** (alternative): Lightweight, more control |
| 174 | +- Must support PostgreSQL, MySQL, SQLite |
| 175 | +- Active maintenance required |
| 176 | + |
| 177 | +```go |
| 178 | +import ( |
| 179 | + "gorm.io/driver/postgres" |
| 180 | + "gorm.io/driver/mysql" |
| 181 | + "gorm.io/gorm" |
| 182 | +) |
| 183 | + |
| 184 | +func initDB() (*gorm.DB, error) { |
| 185 | + dbType := os.Getenv("DB_TYPE") |
| 186 | + dsn := os.Getenv("DATABASE_URL") |
| 187 | + |
| 188 | + var dialector gorm.Dialector |
| 189 | + switch dbType { |
| 190 | + case "mysql": |
| 191 | + dialector = mysql.Open(dsn) |
| 192 | + default: |
| 193 | + dialector = postgres.Open(dsn) |
| 194 | + } |
| 195 | + |
| 196 | + return gorm.Open(dialector, &gorm.Config{}) |
| 197 | +} |
| 198 | +``` |
| 199 | + |
| 200 | +--- |
| 201 | + |
| 202 | +## See Also |
| 203 | + |
| 204 | +- `/home/penguin/code/project-template/docs/standards/DATABASE.md` - Full documentation |
| 205 | +- Alembic migrations: https://alembic.sqlalchemy.org/ |
| 206 | +- PyDAL docs: https://py4web.io/en_US/chapter-12.html |
0 commit comments