# Workshare database design

Status: **built in version 0.7.0 (PostgreSQL) and 0.10.0 (MySQL 8) (27 Nov 2026)** — PostgreSQL storage, import tool, installer, backups and tests are
done. Customer login (accounts linked to Kavion) is the next phase and waits for the backend team's answers.
This document says what lives in the database, why PostgreSQL, the tables as built, and what comes next.

---

## 1. What goes where

Workshare holds two very different kinds of data:

| Data | Size | Changes | Where it should live |
|---|---|---|---|
| **Who**: accounts, members of a model, roles | Small | Rarely | **Database** |
| **Who owns what**: borrowed worksets and elements, requests | Small rows, many | Often (every borrow / sync) | **Database** |
| **History list**: version number, author, date, comment, counts | Small rows | One row per sync | **Database** |
| **Audit**: who removed whom, who restored, who deleted | Small rows | Append only | **Database** |
| **Limits**: models / storage per customer or plan | Small | Rarely | **Database** (`accounts.plan`, used once login is in) |
| **The house itself**: floor map + interior per version | **Up to 20 MB each**, compressed ~1.5 MB | One file per version, never changed | **Files / object storage** (Cloudflare R2), not the database |

Big house documents don't belong in database rows: they would make the database huge, backups slow and every
query heavier. The standard pattern is **database for the index and the relations, object storage for the
blobs**, with the database row storing the object's key.

**Customer accounts** themselves (mobile, name, password/login) already live in the **Kavion backend**
(`parent.globalinfocloud.in`). Workshare should **not** copy them: it stores only the Kavion user id plus a
display-name cache, and asks the Kavion backend to validate logins (see `kavion-login-and-workshare-auth-plan.md`).

---

## 2. Which database

| Option | Good | Less good | Verdict |
|---|---|---|---|
| **PostgreSQL** | Free, very reliable, row locks and advisory locks (one sync per model even with several servers), arrays/JSON columns, mature backups | One more service to run (or a managed one) | **Recommended** |
| Same engine as the Kavion backend (MySQL / SQL Server, whichever it uses) | Your company already runs, backs up and knows it | Depends on access; MySQL is fine too, SQL Server costs licences on Linux | **Good alternative**: ask what the backend uses |
| SQLite (one file, no server) | Nothing to install | One process only, so no scaling; Node needs a native module or the still-new built-in one | Only as a stepping stone |
| MongoDB | Stores documents naturally | Ownership and request rules are relational; weaker multi-row transactions for this use | Not recommended |

---

## 2b. MySQL 8 (0.10.0)

The company server runs MySQL 8, so Workshare supports it as well (`mysql://...`). The tables below exist the same
way in MySQL (`src/db/mysql.js`, its own migration list), with these MySQL forms: `JSON` instead of `JSONB`,
`DATETIME(3)` (UTC) instead of `TIMESTAMPTZ`, `VARCHAR` keys, `utf8mb4_bin` (ids compare exactly), bulk
`INSERT ... ON DUPLICATE KEY UPDATE` instead of `ON CONFLICT`, `GET_LOCK` instead of advisory locks. Ownership rows
reference their model (cascading delete) rather than their member, since MySQL has no deferred foreign keys.
MySQL re-sorts the keys inside JSON documents; the server compares records independent of key order.

## 3. Tables (as built, `src/db/schema.js` migration 1)

| Table | One row per | Main columns (besides `model_id`) |
|---|---|---|
| `accounts` | Kavion customer (empty until login is connected) | `kavion_user_id` unique, `display_name`, `plan`, `blocked_at` |
| `models` | house project | `id`, `name`, `join_code_hash` (unique; the code itself is never stored), `review_mode`, `latest_version`, `created_at`, `updated_at` |
| `members` | person in a model | `member_id`, `account_id` → accounts, `display_name`, `is_admin`, `trusted`, `removed`, `joined_at`, `last_seen_at`, `last_sync_at` (member keys only as SHA-256 hash) |
| `workset_owners` | borrowed workset (Door, Window, …) | `workset`, `member_id` |
| `element_owners` | borrowed element | `element_key`, `member_id` |
| `element_versions` | element | `element_key`, `version` it last changed in (conflict check) |
| `edit_requests` | editing request | `request_id`, `from_member`, `to_member`, `status`, `created_at`, `closed_at` |
| `versions` | synchronize / restore | `version`, `author_member`, `author_name`, `kind`, `comment`, `added/changed/removed/other`, `pruned` |
| `submissions` | change waiting for review | `submission_id`, `author_member`, `status` |
| `audit_log` | admin/membership action | `at`, `actor_member`, `action`, `details`, `client_ip` — no foreign key, outlives deleted models |
| `schema_migrations` | applied migration | `version`, `name`, `applied_at` |

Migration 2 (0.8.0) adds `models.deleted_at`: set while a model is in the trash (restorable by its admin for
`WORKSHARE_TRASH_DAYS`), then the hourly housekeeping deletes the model's rows and folder. `audit_log` entries older
than `WORKSHARE_AUDIT_DAYS` (365) are removed by the same housekeeping.

Migration 3 (0.9.0) links members to Kavion accounts: `members.account_ref` = `accounts.kavion_user_id` =
`k1:` + HMAC-SHA256(`WORKSHARE_ACCOUNT_SECRET`, mobile number), and `accounts.hint` = `******3210`. The database holds
no mobile numbers and no tokens; `members.account_id` points at the `accounts` row.

Design choices:
- **Columns + `doc`.** Main tables have real columns for queries and reports **and** a `doc` JSONB column with the
  complete record as the server uses it. Loading rebuilds from `doc`, so nothing can be lost between server and
  database (tested: after every kind of request, a fresh load equals the server's memory exactly). Both are written
  from the same object in one statement, so they never disagree.
- **Deleting a model** cascades to all its rows; the audit entry stays.
- **Ownership** rows point at their member (deferred foreign keys), so an owner can't exist without a member.
- **House files stay files** (`v<N>.json.gz`, `h<N>.json.gz`, `s-<id>.json`) in `/var/lib/workshare/models/<id>`.
  The database is the index. Phase 3 can move them to Cloudflare R2 without changing the tables.

Example questions the database now answers directly:
```sql
SELECT m.name, m.latest_version FROM models m JOIN members x ON x.model_id = m.id
 WHERE x.display_name = 'Ann' AND NOT x.removed;                      -- houses of a member
SELECT version, author_name, comment, created_at FROM versions
 WHERE model_id = '<id>' ORDER BY version DESC LIMIT 10;              -- recent history
SELECT at, action, actor_member, client_ip FROM audit_log ORDER BY id DESC LIMIT 20;   -- who did what
```

## 4. How it works, and what's next

**Correctness.** Each request that changes something runs, then commits all its rows in **one transaction**, and only
then answers. If the commit fails, the app gets HTTP 503 ("try again"), nothing is half-written, and the server
reloads that model from the database. Writes are diff-based (a one-element sync writes ~5 rows; a 2,000-element
house the first time ~2,000). House files are written before the commit and old ones deleted after it.

**Running it.** Local PostgreSQL on the Workshare server, set up by `deploy/linux/install-linux.sh`: unix socket,
peer login (no password exists; only the `workshare` Linux user gets in), not reachable from the network. A managed
database works with `WORKSHARE_DATABASE_URL=postgres://user:pw@host/db` (TLS + certificate check by default). Nightly
backup = `pg_dump` + house files in one archive (restore tested). Still **one Workshare process** per database and
data folder (the worker threads inside it split the models).

| Phase | What | Status |
|---|---|---|
| 2 | PostgreSQL for the tables above, import of existing models, installer, backups, tests | **Done (0.7.0)** |
| 1 | Customer login: Workshare checks the Kavion token; members linked to `accounts` | **Built (0.9.0)**, switched on after the API check |
| 3 | House files to Cloudflare R2 | Later |
| 4 | Several Workshare servers behind a load balancer (needs per-model locking across processes) | Only when one server isn't enough |

Tests (all run on a real PostgreSQL, also in GitHub Actions): driver 25, store round-trip/outage 32, import 11,
backup/restore 6, and the existing HTTP, production, version-check and pool suites (94 + 30 + 26 + 13, also with 2
workers) again in database mode.

---

## 5. Questions still open (for the login phase)

1. **Which database does the Kavion backend use** (MySQL, SQL Server, PostgreSQL…)? Same engine = one thing to run and back up.
2. Can Workshare get **its own database** (or schema) there, or should it run its own PostgreSQL on the Workshare server?
3. The login questions from `kavion-login-and-workshare-auth-plan.md` (token check endpoint, expiry, stable user id).
4. Are there **plans** (free / paid) with different limits?
