Data Layer
Database Architecture
RAFIQ uses a dual-database architecture: SQLite as the always-available local store and Supabase as the cloud replica. All writes succeed locally first. Cloud sync is a background best-effort operation — never a blocker.
SQLite
WAL · FTS5 · JSON1
Primary local store. Always writable. WAL mode for concurrent reads.
Supabase
PostgreSQL · RLS · Realtime
Cloud replica. Receives sync pushes. Provides multi-device access.
Sync Engine
30s cycle · Retry queue
Background service. Reads sync_queue, pushes to Supabase, pulls remote changes.
Conflict Resolver
LWW · Vector clocks
Last-Write-Wins by updated_at. Vector clocks for emergency_states.
Table Schema · 12 tables
SQLite primary · Supabase replica · sync_queue-driven push
| Table | Key Columns | Sync Direction | Priority |
|---|---|---|---|
| patients | id, name, dob, conditions[], medications[] | ↑↓ Bidirectional | Critical |
| wearable_metrics | id, patient_id, bpm, spo2, steps, ts | ↑ Push-only | High |
| alerts | id, type, severity, source, status, ts | ↑↓ Bidirectional | Critical |
| reminders | id, patient_id, type, scheduled_at, done | ↑↓ Bidirectional | High |
| ai_logs | id, model, input, output, latency_ms, ts | ↑ Push-only | Medium |
| ai_memory | id, patient_id, context_json, updated_at | ↑↓ Bidirectional | High |
| sync_queue | id, table_name, op, payload, status, retries | ⊘ Local-only | System |
| mqtt_logs | id, topic, payload, qos, ts | ⊘ Local-only | Low |
| system_events | id, service, event, data, ts | ⊘ Local-only | Low |
| emergency_states | id, type, severity, active, resolved_at | ↑↓ Bidirectional | Critical |
| automation_rules | id, trigger_json, action_json, enabled | ↑↓ Bidirectional | High |
| device_status | id, device_id, room, state, last_seen | ↑ Push-only | Medium |
Service Read/Write Access Matrix
| Service | patients | wearable | alerts | ai_logs | sync_queue | emergency |
|---|---|---|---|---|---|---|
| Core Engine | R/W | R/W | R/W | R | R/W | R/W |
| AI Orchestrator | R | R | R | R/W | — | R |
| Sync Engine | R | R | R | R | R/W | R |
| Emergency Engine | R | R | R/W | — | — | R/W |
| HA Bridge | — | — | R | — | — | R |
| FastAPI (REST) | R/W | R | R/W | R | R | R |
Database Mission Control
Structured SQL infrastructure · ownership · sync topology · entity relationships
SQLite Init + Sync Queue
-- SQLite initialization with WAL mode
PRAGMA journal_mode = WAL; -- Write-Ahead Logging
PRAGMA synchronous = NORMAL; -- fsync on WAL checkpoints
PRAGMA cache_size = -65536; -- 64MB page cache
PRAGMA foreign_keys = ON; -- Referential integrity
PRAGMA auto_vacuum = INCREMENTAL; -- Reclaim space incrementally
PRAGMA wal_autocheckpoint = 1000; -- Checkpoint every 1000 pages
-- Sync queue table (core of offline-first architecture)
CREATE TABLE IF NOT EXISTS sync_queue (
id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))),
table_name TEXT NOT NULL,
operation TEXT NOT NULL CHECK (operation IN ('INSERT','UPDATE','DELETE')),
row_id TEXT NOT NULL,
payload JSON NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
retries INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);Auto-Queue Trigger
-- Auto-queue writes for sync (example: wearable_metrics)
CREATE TRIGGER wearable_metrics_sync_insert
AFTER INSERT ON wearable_metrics
BEGIN
INSERT INTO sync_queue (table_name, operation, row_id, payload)
VALUES (
'wearable_metrics', 'INSERT', NEW.id,
json_object('id', NEW.id, 'patient_id', NEW.patient_id,
'bpm', NEW.bpm, 'spo2', NEW.spo2, 'ts', NEW.ts)
);
END;Last-Write-Wins (default)
Applied to all non-critical tables. The row with the highest updated_at timestamp wins. Simple, predictable, and fast to resolve. Works well for wearable metrics, device states, and AI logs.
Vector Clocks (emergency data)
Applied to emergency_states and alerts. Tracks causality — if an emergency was resolved locally but the cloud still shows active, the resolution wins. Prevents false-clear scenarios.