# Migrate from Supabase or Firebase
Source: https://sovaria.in/docs/migrate-from-supabase-or-firebase

Move a Supabase or Firebase project to Sovaria with one command: schema and row-level security, users who keep their passwords, data, documents, storage, and a report of anything that needs a look.

**What moves:** from Supabase, the `public` schema (tables, views, functions, triggers, RLS policies), `auth.users` with their ids, verified state and passwords, every row, and storage buckets with their files. From Firebase, Auth users with their passwords, every Firestore collection and subcollection, Cloud Storage files, and a report that maps each security rule to a Sovaria policy.

**Users keep their passwords.** Supabase stores bcrypt hashes, which Sovaria uses as they are. Firebase uses a modified scrypt: Sovaria checks it with your project's hash parameters (Firebase's own: rounds 8, memory cost 14; higher values are refused) on the user's first sign-in, then stores a bcrypt hash, so nobody has to reset their password. An import never sends emails and never runs sign-up hooks or function triggers.

## Prerequisites

- A Sovaria project, and the CLI signed in as an owner or admin of its organization: `npm install -g @sovaria/cli` (or `pip install sovaria-cli`), `sov login`, `sov scope pick`.
- Supabase: the PostgreSQL client tools (`pg_dump`, `psql`, version 15 or newer), the database connection string (Supabase › Project settings › Database) and, for storage, the service_role key.
- Firebase: a service account JSON with read access to Firestore and Storage, the Firebase CLI for `firebase auth:export`, and the password hash parameters (Firebase console › Authentication › Users › ⋮ › Password hash parameters).

## From Supabase

Terminal:
```bash
# 1. check everything, write nothing
sov import supabase \
  --db-url 'postgresql://postgres:PASSWORD@db.REF.supabase.co:5432/postgres' \
  --supabase-url https://REF.supabase.co --service-key "$SUPABASE_SERVICE_ROLE_KEY" --dry-run

# 2. import (schema, then users, then data, then storage)
sov import supabase --db-url '...' --supabase-url https://REF.supabase.co --service-key "$SUPABASE_SERVICE_ROLE_KEY"
```

**How policies change:** Sovaria databases have no `anon` or `authenticated` role. A policy `TO authenticated` becomes `TO public` with `auth.uid() IS NOT NULL` added to its condition; `TO anon` adds `auth.uid() IS NULL`; a `service_role`-only policy is dropped, because the service key already bypasses row-level security. `auth.uid()`, `auth.jwt()` and `auth.role()` work as in Supabase. GRANTs are dropped: your app's queries run as the project's app role, which can read and write your tables subject to RLS.

Use `--only schema,auth` to run parts on their own, and `--rows-per-insert 1` if a very wide table makes a statement too large.

## Your app code

Swap the import and the two values from the console's **Connect** panel. With `results: 'supabase'`, awaited queries resolve to `{ data, error, count, status }` and never throw, so supabase-js code keeps working; without it they resolve to the rows and throw a `SovariaError` (`.safe()` gives `{ data, error }` for one query, `.throwOnError()` the rows in supabase mode).

JavaScript:
```js
import { createClient } from '@sovaria/sdk'      // was: '@supabase/supabase-js'
const supabase = createClient('https://<project-ref>.sovarias.in', '<anon-key>', { results: 'supabase' })

const { data: books, error, count } = await supabase.from('books').select('id,title', { count: 'exact' }).eq('genre', 'sci-fi')
const { data: club } = await supabase.from('clubs').insert({ name }).select().single()
const { count: unread } = await supabase.from('messages').select('*', { count: 'exact', head: true }).is('read_at', null)

const { data, error: signInError } = await supabase.auth.signInWithPassword({ email, password })
const { data: { user } } = await supabase.auth.getUser()
const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => render(session))
const { data: upload } = await supabase.storage.from('avatars').upload(`${user.id}/me.png`, file, { upsert: true })
```

| supabase-js | Sovaria |
|---|---|
| `from(t).select / insert / update / upsert / delete`, filters, `order`, `range`, `single`, `maybeSingle`, embeds | The same (`eq(col, null)` means `IS NULL` in every SDK). `insert(object)` gives a list in supabase mode, one row otherwise. |
| `auth.signUp({ email, password, options: { data } })`, `signInWithPassword`, `signInWithOtp`, `verifyOtp`, `signInWithOAuth`, `signInAnonymously`, `getUser`, `updateUser`, `signOut` | The same, resolving `{ data, error }`; `options.data` is stored with the new account. |
| `auth.getSession()` | Returns the session (or `null`) directly, without a network call, instead of `{ data: { session } }`. `expires_at` is in milliseconds. |
| `auth.onAuthStateChange` | Returns a function that stops listening, which also has `data.subscription.unsubscribe()`. |
| `storage.from(bucket)` | The same in JavaScript and Python (`from_`). In Swift, Kotlin and Dart buckets are `sovaria.files.from(bucket)`. |
| supabase-py: `supabase.table(t)…execute()`, `res.data` | `sov.table(t)` / `sov.from_(t)`; the result is the rows and also has `.data` and `.count`. `sov.auth.sign_in_with_password({...})`, `sov.storage.from_(b)` as in supabase-py. |

## From Firebase

Terminal:
```bash
firebase auth:export users.json --format=json --project YOUR_PROJECT
# hash.json: {"base64_signer_key": "...", "base64_salt_separator": "Bw==", "rounds": 8, "mem_cost": 14}

sov import firebase --service-account sa.json \
  --auth-export users.json --hash-config hash.json --rules firestore.rules --dry-run
sov import firebase --service-account sa.json \
  --auth-export users.json --hash-config hash.json --rules firestore.rules
```

**How data is laid out:** every document keeps its Firestore path: `users/{id}` stays in `users` and `users/{id}/orders/{id}` stays a subcollection of that user. Ids with characters Sovaria keys don't allow are cleaned, and the report lists them. Firebase uids aren't UUIDs, so users get new ids; the import writes `sovaria-import-uid-map.json` and, by default, replaces old uids with the new ids in your documents and in document ids and paths, so `users/{uid}` is still the user's own document (`--keep-uids` to turn that off). Import Auth first so the map exists.

**Rules:** with `--rules`, `sovaria-rules-report.md` lists every rule with its Sovaria equivalent (public, signed-in users, owner only, or a custom policy). Nothing is applied automatically: add the policies, then check them with a simulation ([Tutorial: prove your table is private before you ship](https://sovaria.in/docs/tutorial-secure-a-table)).

## After the import

- Read `sovaria-import-report.json`: skipped users (already in the project), failed rows, policy notes, renamed keys.
- Run `sov sim run --fail-on critical` to prove each kind of caller reaches only what it should.
- Point your app at Sovaria. From Supabase, keep supabase-js: change the URL and anon key to your project's, and `from()` / `rpc()` calls work as before (see [HTTP API](https://sovaria.in/docs/http-api), "Tables over REST"). From Firebase, keep your Firestore code and change its import to `@sovaria/sdk/firestore` (see [Firebase-style code (Firestore API)](https://sovaria.in/docs/firestore-compat)); Auth and Storage calls move to the Sovaria SDK — see [Quickstart](https://sovaria.in/docs/quickstart).
