# Versioning System Architecture

**System design, data flow, and architectural decisions**

## System Overview

The Universal Versioning System is a relational database-backed solution for tracking all changes to entities throughout their lifecycle. It uses PostgreSQL triggers, session variables, and type-safe relational tables to provide automatic, transparent versioning.

## Design Philosophy

### Core Principles

1. **Automatic & Transparent** - Versioning happens automatically via triggers
2. **Pure Relational** - No JSONB storage, all fields are typed columns
3. **Audit-First** - Every change is attributed to a user and optionally a submission
4. **Type-Safe** - Foreign keys and constraints enforce data integrity
5. **Performance-Conscious** - Proper indexing and cleanup mechanisms

### Why Not JSONB?

The previous system stored versions as JSONB blobs. We migrated to relational for:

| Issue with JSONB | Relational Solution |
|------------------|---------------------|
| Not queryable without JSONB operators | Standard SQL WHERE clauses |
| No type safety | Column-level types and constraints |
| Poor performance on large datasets | Indexed columns |
| Can't use foreign keys | Full referential integrity |
| Complex RLS policies | Standard column-level RLS |

## High-Level Architecture

```mermaid
graph TB
    subgraph "Frontend Layer"
        UI[React Components]
        HOOKS[React Hooks]
    end
    
    subgraph "Backend Layer"
        EDGE[Edge Functions]
        DB[(PostgreSQL)]
        TRIGGERS[Database Triggers]
    end
    
    UI --> HOOKS
    HOOKS --> DB
    EDGE --> SESSION[Set Session Variables]
    SESSION --> DB
    DB --> TRIGGERS
    TRIGGERS --> VERSIONS[Version Tables]
    
    style VERSIONS fill:#4CAF50
    style TRIGGERS fill:#2196F3
    style SESSION fill:#FF9800
