# Documents
Source: https://sovaria.in/docs/documents-overview

Store JSON documents in collections, read them by id or list a collection, and control exactly who can see and change them.

Documents are JSON objects stored under a **collection** and an **id**, for example `carts/7f3a…`. Use them for data whose shape varies or that you always read whole: carts, drafts, settings, form submissions. For data you filter, join or aggregate, use [tables](https://sovaria.in/docs/database) instead.

Documents are kept in your project's own Postgres database (in the table `sov_documents`), so they are covered by its backups, and the same [row-level security](https://sovaria.in/docs/row-level-security) rules language decides who may read them.

- [Querying documents](https://sovaria.in/docs/document-queries): Filters on any field, sorting, cursors, counts and indexes.
- [Live listeners](https://sovaria.in/docs/live-listeners): Results that update themselves: added, modified, removed.
- [Transactions and transforms](https://sovaria.in/docs/document-transactions): All-or-nothing writes, read-then-write, increment, arrayUnion.

## Write, read and delete

JavaScript:
```js
// Create or replace
await sovaria.data.docPut('carts', userId, { items: [{ sku: 'BK-1', qty: 2 }] })

const { data } = await sovaria.data.docGet('carts', userId)   // { key, data, found }
await sovaria.data.docDelete('carts', userId)

// Every document in one collection (note the colon)
const { documents, truncated } = await sovaria.data.docScan({ prefix: 'carts:', limit: 100 })
```

Python:
```python
from sovaria.data import DataClient

carts = DataClient(sovaria).collection("carts")

await carts.insert({"items": [{"sku": "BK-1", "qty": 2}]}, document_id=user_id)
cart = await carts.get(user_id)
await carts.update(user_id, {"coupon": "SPRING"})     # merges top-level fields
paid = await carts.find({"status": "paid"}, limit=50)  # equality filter on fields
n = await carts.count({"status": "paid"})
await carts.delete(user_id)
```

cURL:
```bash
curl -s -X POST $URL/api/v1/data/doc/carts/$USER_ID \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"data":{"items":[{"sku":"BK-1","qty":2}]}}'

curl -s -X POST $URL/api/v1/data/query/scan \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"prefix":"carts:","limit":100}'
```

## Collections, ids and listing

- Collection names and ids may contain letters, digits, `-` and `_`. Nest collections with `/`: `orders/123/notes`.
- Writing to an existing id **replaces** the whole document; earlier contents are not kept. In Python, `update()` reads the document and merges your fields in. If you need history, write each change as its own document (for example `carts/<id>/changes`).
- Listing (`scan`) matches keys of the form `collection:id`. Use the prefix `carts:` for one collection — `carts` alone would also match a collection named `cartsArchive`.
- A scan returns up to `limit` documents (default 100, at most 10,000) in key order, each as `{key, data}`. `truncated: true` means there are more; ask for the next page with `start_key` set to the last `key` you received (it is included again, so skip it).
- Scans only return documents the caller is allowed to read.

## Who can read and write

Console members and the service role key can read and write every document. **App users and anonymous visitors get nothing until you allow it.** Each document records the app user who created it in `owner_id`, so the common rules are one line of SQL each. Run them in the **SQL editor**:

SQL editor:
```sql
-- Each user reads and writes only their own carts
create policy carts_own on sov_documents for all
  using (collection = 'carts' and owner_id = auth.uid()::text)
  with check (collection = 'carts' and owner_id = auth.uid()::text);

-- Everyone, signed in or not, can read the public catalogue
create policy catalogue_read on sov_documents for select
  using (collection = 'catalogue');

-- Only users with the app role "staff" can change it
create policy catalogue_staff on sov_documents for all
  using (collection = 'catalogue' and auth.has_role('staff'))
  with check (collection = 'catalogue' and auth.has_role('staff'));
```

You can also allow access per collection with a project policy under **Policies** (in rules `ctx.action` is `doc:read` for gets, queries and listeners, `doc:write` or `doc:delete`, and `ctx.resource.name` is the collection — [Policy language (SPL)](https://sovaria.in/docs/policy-language)). A refused write returns `403` with `Row policy denied this document change`.

**No rule, no access.** A collection that neither a policy nor a row policy on `sov_documents` names is closed to app users and visitors: reads, queries, writes and deletes answer `403`, never an empty list or a delete that silently did nothing. If your app gets `403` on a collection, add the rule; it doesn't mean the collection is empty. Your team (console, CLI, service key) is not affected.

> **Tip:** Test your rules before shipping: open **Authentication → Users**, pick a user and start a **test session**, or use **Simulation**.

## History and recovery

| Question | Answer |
|---|---|
| Are earlier versions of a document kept? | No. A write replaces the document and a delete removes it; there is no per-document version history or trash. |
| Does Version history cover documents? | No. [Version history: see, undo and restore changes](https://sovaria.in/docs/version-history) records configuration — policies, tables, functions, settings, buckets, keys — not document contents. |
| Is there an audit trail of document changes? | Not of their contents. Who changed rules and settings is in the audit log ([Audit log](https://sovaria.in/docs/audit-logs)). |
| How do I get deleted or overwritten documents back? | Documents live in your project's database (`sov_documents`), so the daily backups include them. Restoring a backup restores the whole database to that day ([Backups and recovery](https://sovaria.in/docs/backups-and-recovery)). |

If your app needs history (edits to an order, revisions of a page), keep it yourself: write each change as its own document in a sub-collection such as `orders/<id>/revisions`, with the time and author, and let users read but not edit it ([Transactions, batches and field transforms](https://sovaria.in/docs/document-transactions) writes the document and its revision together).

## In the console

**Collections** lists every collection with its document count. Open one to browse (100 documents at a time), edit or delete documents as JSON, import JSON, JSON Lines or CSV and export a collection. The **Query**, **Indexes** and **Rules** tabs run field queries, manage indexes and show who may read and write each collection.

## From the CLI

CLI:
```bash
sov collections list
```

## Limits

- A document is a JSON object (not an array or a single value).
- Documents count towards your database size, which depends on your plan — see [Plans, usage and limits](https://sovaria.in/docs/plans-and-limits).
