# MAYA OS ENTERPRISE — MYSQL 8.4 DATABASE ENGINEERING GUIDE

## 1. Mandatory Engine Posture

`backend/config/settings.py` validates at startup that `DB_ENGINE == "mysql"` and configures PyMySQL (`backend/config/__init__.py`) with:

- **Engine**: `InnoDB` (full ACID transactions & row-level locking)
- **Charset / Collation**: `utf8mb4` / `utf8mb4_unicode_ci` (full Nepali Devanagari Unicode support)
- **Strict SQL Mode**: `STRICT_TRANS_TABLES,STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION`
- **Transaction Isolation**: `READ-COMMITTED` (avoids InnoDB gap-lock serialization stalls under high concurrent multi-user posting)
- **Connection Health**: `CONN_MAX_AGE=300` + `CONN_HEALTH_CHECKS=True` + connect/read/write timeouts
- **Deadlock Retry**: `apps/system_admin/mysql_concurrency.py` (`run_with_deadlock_retry`, `@mysql_deadlock_retry`) retries MySQL `1205`/`1213` transient lock waits cleanly.

Apply `deployment/mysql/my.cnf` on your MySQL server (`/etc/mysql/conf.d/maya-os.cnf`) before going live.

## 2. Least-Privilege Database Accounts

Use `deployment/mysql/init_users.sql.template` to separate duties across 4 MySQL users:

- `maya_mig`: Schema migrations & upgrades only (`ALL PRIVILEGES ON maya_os.*`)
- `maya_app`: Live API / worker runtime (`SELECT, INSERT, UPDATE, DELETE, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE` — no `DROP`/`ALTER`)
- `maya_bkp`: Logical backups (`SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER, RELOAD, PROCESS`)
- `maya_mon`: Read-only health/monitoring probes (`PROCESS, REPLICATION CLIENT`, `SELECT`)

## 3. Verifying MySQL Posture

```bash
backend/.venv/bin/python backend/manage.py shell -c "
from apps.system_admin.mysql_concurrency import verify_mysql_production_posture
import json; print(json.dumps(verify_mysql_production_posture(), indent=2))
"
```

## 4. Schema Migration Integrity & Uniqueness

All Django migrations target MySQL natively without PostgreSQL-specific operators or partial indexes (`models.W036` resolved cleanly via nullable unique keys such as `ChequeLeaf.issued_unique_key`). Always verify schema parity after pull/upgrade:

```bash
backend/.venv/bin/python backend/manage.py makemigrations --check --dry-run
backend/.venv/bin/python backend/manage.py migrate --check
```

