# Firebase-style code (Firestore API)
Source: https://sovaria.in/docs/firestore-compat

Keep your Firestore code: import from @sovaria/sdk/firestore instead of firebase/firestore and point it at your Sovaria project.

`@sovaria/sdk/firestore` has the functions of Firebase's modular Firestore API on top of Sovaria documents, so moving an app is an import change. Queries, live listeners, batches and transactions are the real Sovaria ones described in [Querying documents](https://sovaria.in/docs/document-queries), [Live listeners](https://sovaria.in/docs/live-listeners) and [Transactions, batches and field transforms](https://sovaria.in/docs/document-transactions).

Before (Firebase):
```js
import { initializeApp } from 'firebase/app'
import { getFirestore, collection, query, where, orderBy, limit, onSnapshot } from 'firebase/firestore'

const db = getFirestore(initializeApp(firebaseConfig))
```

After (Sovaria):
```js
import { createClient } from '@sovaria/sdk'
import { getFirestore, collection, query, where, orderBy, limit, onSnapshot } from '@sovaria/sdk/firestore'

const sov = createClient('https://<ref>.sovarias.in', '<anon key>')
const db = getFirestore(sov)

// Everything below is unchanged Firebase code.
const q = query(collection(db, 'rooms', roomId, 'messages'), where('hidden', '==', false), orderBy('sentAt', 'desc'), limit(50))
const stop = onSnapshot(q, (snap) => render(snap.docs.map((d) => ({ id: d.id, ...d.data() }))))
```

## What is supported

| Area | Functions |
|---|---|
| References | `collection`, `collectionGroup`, `doc` (path segments or a full path, nested subcollections, auto ids), `documentId()` |
| Queries | `query`, `where` (`==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `not-in`, `array-contains`, `array-contains-any`), `or`, `and`, `orderBy`, `limit`, `limitToLast`, `startAt`, `startAfter`, `endAt`, `endBefore` (values or snapshots) |
| Reads | `getDoc`, `getDocs`, `getCountFromServer`, `getAggregateFromServer` with `count`, `sum`, `average`, `onSnapshot` (returns its unsubscribe function; `docChanges()` on snapshots) |
| Vector search | `findNearest(query, { vectorField, queryVector, limit, distanceMeasure, distanceResultField, distanceThreshold })` (or `query.findNearest(…).get()`), `vector([…])` values; see [Vector search on documents](https://sovaria.in/docs/document-vector-search) |
| Writes | `setDoc` (with `{ merge: true }`), `addDoc`, `updateDoc` (object or field/value pairs, dotted paths), `deleteDoc` |
| Field values | `serverTimestamp`, `increment`, `arrayUnion`, `arrayRemove`, `deleteField`, `Timestamp` |
| Atomic | `writeBatch` (`set` / `update` / `delete` / `commit`), `runTransaction` (retried on conflict) |

## Differences from Firebase

- Times are stored as ISO-8601 strings. `Timestamp`, `Date` and `serverTimestamp()` all become one, so ordering and range filters work; read them back with `new Date(value)` or `Timestamp.fromDate(new Date(value))`.
- Offline persistence works the Firebase way — `initializeFirestore(sov, { localCache: persistentLocalCache() })` or `enableIndexedDbPersistence(db)` — and snapshots report `metadata.fromCache` and `metadata.hasPendingWrites`. Multi-tab coordination isn't there yet: use one tab per app, or each tab keeps its own queue. See [Offline-first apps](https://sovaria.in/docs/offline-first).
- Access is decided by your collection rules and row policies, not `firestore.rules`. `sov import firebase --rules firestore.rules` writes a report of the equivalent of each rule. See [Documents](https://sovaria.in/docs/documents-overview).
- One rule covers a subcollection under every document: write the path with `*` for the document id, like `users/*/orders`. A `*` stands for exactly one path segment and the depth must match, so `users/*/orders` covers `users/alice/orders` but not `users/alice` or `users/alice/orders/o1/items`. In a policy, compare `ctx.resource.pattern` (`ALLOW IF ctx.resource.pattern == "users/*/orders"`); `ctx.resource.name` keeps the full path. Permission claims work the same way: `collection:users/*/orders:read`.
- Document ids and collection names use letters, digits, `_ . @ -` (up to 256). The Firebase import cleans other characters and lists every renamed id.

Moving the data too: [Migrate from Supabase or Firebase](https://sovaria.in/docs/migrate-from-supabase-or-firebase) imports Firebase Auth users with their passwords, every collection and subcollection at the same paths, and Storage files.
