# Migrate from Neon or PostgreSQL
Source: https://sovaria.in/docs/migrate-from-postgres

Move Neon, RDS, Railway or any Postgres to Sovaria with one command (schema, data and your users with their passwords) or with pg_dump and psql, then lock it down, validate, cut over and roll back.

(Diagram: sov import postgres reads your database and writes three things into Sovaria)

|  | `sov import postgres` | pg_dump and psql by hand |
|---|---|---|
| Schema, data, sequences | Yes, as one recorded migration plus the rows | Yes, restored straight into the database |
| Policies for your own roles | Rewritten as `TO public`, each one noted in the report | Fail to restore until you edit them |
| Your app's users | Imported with their passwords (formats below) | Created by hand; users reset their password |
| Best for | Most apps, up to a few GB | Very large databases, custom restore options |

## The fast way: sov import postgres

1. **Get the source connection string** — Neon: Dashboard › Connect, with **Connection pooling off** (the direct host, without `-pooler`): `pg_dump` needs a session, not a pooled connection. RDS, Railway, Render, Supabase-free Postgres: the usual `postgresql://` URL. `pg_dump` and `psql` version 16 or newer must be on your PATH.
2. **Pick the Sovaria project** — `sov login`, then `sov scope pick` (or pass `--org` and `--project`).
3. **Dry run** — Everything is read and checked against your Sovaria project; nothing is written. Read `sovaria-import-report.json`.
```bash
sov import postgres \
  --db-url "postgresql://USER:PASSWORD@ep-cool-name-123456.eu-central-1.aws.neon.tech/neondb?sslmode=require" \
  --users-query "select id, email, password_hash, email_verified, name from users" \
  --dry-run
```
4. **Import** — The same command without `--dry-run`. Run parts on their own with `--only schema`, `--only data` or `--only users`.

| Part | What happens |
|---|---|
| Schema | The `public` schema (or `--schema`) as **one migration** named `import_postgres_schema`, so it shows in [Version history: see, undo and restore changes](https://sovaria.in/docs/version-history) and is all or nothing. Owners, grants and `SET` lines are dropped. Extensions the dump needs are listed in the report: turn them on under **Schema › Extensions** first ([Extensions](https://sovaria.in/docs/database-extensions)). |
| Policies | Policies written `TO app_user` (or any role of your old database) become `TO public`, each with a note: add `auth.uid()` or `auth.has_role('…')` to the condition where it should apply to some users only ([Auth helpers in SQL](https://sovaria.in/docs/auth-helpers)). |
| Data | Every row as `INSERT` statements (`--rows-per-insert`, default 50), then the sequences, so new ids continue after the highest one. |
| Users | Only with `--users-query`: one `SELECT` on your old database returning `id`, `email`, `password_hash` and optionally `email_verified`, `name`, `phone`. No emails are sent and no sign-up hooks run. |

### Which passwords carry over

The format of each hash is recognised on its own, row by row. Users with a supported hash sign in with their old password; on that first sign-in Sovaria re-hashes it with bcrypt.

| Hash looks like | Comes from | Kept |
|---|---|---|
| `$2a$` / `$2b$` / `$2y$…` | bcrypt: Node `bcrypt`/`bcryptjs`, Rails Devise, Laravel, Spring, Supabase | Yes |
| `$argon2id$v=19$m=…` | Argon2: `node-argon2`, `argon2-cffi`, Laravel, Lucia, Auth libraries | Yes, up to m = 64 MiB, t = 10, p = 8 |
| `pbkdf2_sha256$600000$…` | Django | Yes, up to 2,000,000 iterations |
| `<salt>:<128 hex characters>` | Lucia scrypt, Convex Auth | Yes |
| MD5, SHA-1, plain SHA-256, anything else | Older custom code | No: imported without a password; the user signs in with a magic link or resets it |

Users keep their id when it is a UUID. Integer or text ids get a new UUID, and `sovaria-import-uid-map.json` lists `old id → new id` so you can update ownership columns (below).

> **Neon specifics:** Neon branches map to Sovaria [environments](https://sovaria.in/docs/environments-and-staging): import each branch you need into its own environment. Users of **Neon Auth** live in Stack Auth, not in your database (`neon_auth.users_sync` holds no passwords): import them with a query on that table and they sign in with a magic link the first time.

## The manual way: pg_dump and psql

Use this for very large databases or when you need full control of the restore. What moves and what doesn't:

| Part | How it moves |
|---|---|
| Schema, data, sequences, views, functions, triggers | Standard tools: `pg_dump` from the old database, `psql` into Sovaria. |
| Row-level security policies | Come along in the dump; policies for roles Sovaria doesn't have need rewriting (below). |
| Roles, grants, ownership | Not moved — Sovaria manages database roles. Dump with `--no-owner --no-privileges`. |
| Extensions | Only those Sovaria offers ([Postgres in Sovaria](https://sovaria.in/docs/postgres-basics)); superuser-only extensions and schedulers such as `pg_cron` aren't available. |
| Your app's users | Not in Postgres terms: create accounts in Sovaria Auth (below). |
| Cron jobs, `LISTEN/NOTIFY` consumers | Rebuild as function schedules and database change events ([Event triggers](https://sovaria.in/docs/function-triggers), [Database change events](https://sovaria.in/docs/realtime-database-changes)). |

## 1. Prepare

1. **Create the project** — Pick the region closest to your users — it can't be changed later. New Sovaria projects run PostgreSQL 18 (older ones 16); dump with a `pg_dump` of the same or a newer version than your source (it reads older servers).
2. **Check extensions** — Compare what you use with what Sovaria offers; turn the ones you need on first (Schema › Extensions).
```sql
select extname, extversion from pg_extension order by 1;
```
3. **Check the size** — Your plan's database disk must hold the data with room to grow ([Plan limits](https://sovaria.in/docs/plan-limits)).
4. **Get the connection string** — Connect › Database: host `db.<org-id>.sovarias.in`, port `5432`, `sslmode=require` ([Database: connection, compute, disk and backups](https://sovaria.in/docs/settings-database)). It is a team credential that bypasses your Sovaria rules — keep it out of apps.

## 2. Dump and restore

Shell:
```bash
# Schema and data of the public schema, without owners or grants
pg_dump "$OLD_DATABASE_URL" --schema=public --no-owner --no-privileges --format=plain --file=dump.sql

# Into Sovaria; stop at the first error
psql "postgresql://<db-user>:<password>@db.<org-id>.sovarias.in:5432/<database>?sslmode=require" \
  --set ON_ERROR_STOP=1 --single-transaction --file=dump.sql
```

- `--single-transaction` makes the restore all or nothing; fix the error and run it again on an empty database.
- Policies written `TO <role>` for a role Sovaria doesn't have fail to restore. Change them to `TO public` with a condition on the signed-in user — `using (owner_id = auth.uid())` ([Auth helpers in SQL](https://sovaria.in/docs/auth-helpers)).
- If a large table's `COPY` hits the statement timeout, load it on its own with a higher `statement_timeout` (up to your plan's maximum), or split the data ([Pooling and timeouts](https://sovaria.in/docs/settings-pooling-and-timeouts)).

## 3. Record a baseline

Write the restored schema as your first migration, so every later change goes through migrations and your environments stay in step ([Migrations](https://sovaria.in/docs/migrations)):

CLI:
```bash
sov link            # in your app's folder
sov db pull         # writes the current schema to sovaria/.sovaria/remote_schema.sql (a reference, not a migration)
```

## 4. Decide who may read and write

Restored tables are closed to app users until something allows them: a table needs row-level security that is enabled **and** forced, or an access policy ([How access is decided](https://sovaria.in/docs/access-model)).

SQL:
```sql
alter table orders enable row level security;
alter table orders force row level security;
create policy "customers see their orders" on orders
  for select using (customer_id = auth.uid());
```

Then check: the Security advisor lists tables without rules ([Security advisor](https://sovaria.in/docs/security-advisor)), and `sov sim run` shows what every kind of user can do ([Simulate access before you ship](https://sovaria.in/docs/simulation)).

## 5. Users

- If your app kept its own users table, import the accounts with their passwords: `sov import postgres --db-url … --only users --users-query "select id, email, password_hash from users"` ([[#password-formats]]). Users whose hash format isn't supported sign in with a magic link or reset their password.
- Sovaria user ids are UUIDs. Ids that changed are in `sovaria-import-uid-map.json`: load it into a mapping table and update ownership columns, so policies can compare them with `auth.uid()`.

SQL:
```sql
-- After loading sovaria-import-uid-map.json into uid_map(old_id text, new_id uuid)
alter table orders add column owner_id uuid;
update orders o set owner_id = m.new_id from uid_map m where m.old_id = o.user_id::text;
create policy "own orders" on orders for select using (owner_id = auth.uid());
```

## 6. Validate

SQL (run on both):
```sql
-- exact row counts per table
select 'orders' as t, count(*) from orders
union all select 'customers', count(*) from customers;

-- spot-check content: a hash of a table's rows in key order
select md5(string_agg(t::text, ',' order by id)) from orders t;
```

- Counts and hashes match for every table you moved.
- Sequences continue after the highest id (`pg_dump` sets them): insert a test row.
- Your app's test suite passes against a staging environment ([Testing your app](https://sovaria.in/docs/testing)).

## 7. Cut over

1. **Rehearse** — Do the whole move once on a staging environment and time it.
2. **Stop writes** — Put the app in maintenance mode or make the old database read-only.
3. **Move the final data** — Restore again from a fresh dump (into an empty database), then validate.
4. **Switch the app** — Deploy with the Sovaria project URL and keys ([Connect your app](https://sovaria.in/docs/connect-your-app)), and turn writes back on.

## Rolling back

Keep the old database untouched and read-only until you are confident. To roll back, point the app at it again; anything written to Sovaria after the cutover has to be copied back by hand, so keep the window between cutover and decision short.
