Migrating · Platform guides
Coming from Postgres
Convert Postgres tables into schema types, move route-level checks into access policies, replace ORM queries with deployed EdgeQL files and copy your rows.
- API
- —
- In the schema
ext::auth::Identity
What you’ll move#
This guide migrates a Postgres notes app to Napalm. The existing database stores a users table with password hashes, a notes table owned by a user and a join table for shared notes. Today your backend connects through an ORM or raw SQL and appends a per-user WHERE clause to every query.
In Napalm, tables become object types, the join table collapses into a multi link and that WHERE clause moves onto the Note type as an access rule. An export script streams existing rows into your project in batches. If your Postgres database runs on Supabase, see Coming from Supabase for RLS policies, auth.users and Storage.
-- A plain Postgres app's tables, as an ORM would have made them.create table users ( id uuid primary key default gen_random_uuid(), email text unique not null, password_hash text not null, name text not null);create table notes ( id uuid primary key default gen_random_uuid(), owner_id uuid not null references users (id), title text not null, body text not null, created_at timestamptz not null default now());create table note_shares ( note_id uuid not null references notes (id) on delete cascade, user_id uuid not null references users (id), primary key (note_id, user_id));Before you start#
Create a project in the console and sign in with the napalm CLI. Work on an isolated branch until you have rehearsed the entire migration.
# Export table and constraint definitions without row datapg_dump --schema-only --no-owner "$OLD_DATABASE_URL" > old-schema.sql # Draft an initial schema into dbschema/default.gelnapalm schema draft --from old-schema.sql # Or draft directly from a Prisma schemanapalm schema draft --from prisma/schema.prisma # Create an isolated branch and push your schema and queriesnapalm branches create notes rehearsalnapalm schema push notes --branch rehearsalnapalm queries push notes --branch rehearsalProjects expose no SQL port or wire connection string, so psql, ORMs and connection poolers do not connect directly. Your app calls deployed EdgeQL queries over HTTPS instead. Each section below converts one part of the Postgres app. A coding agent can automate most of that conversion, and Moving with a coding agent lists the exact files and prompt to provide.
Turn tables into types#
Each SQL table becomes an object type and each column becomes a property. Foreign keys become typed links, and join tables collapse into multi links. Napalm assigns every imported object a new UUID id while preserving the original primary key in old_id during migration.
Drafted types and links
The CLI drafts object types and replaces join tables with multi links.
napalm schema draft generates an initial dbschema/default.gel from old-schema.sql. Apps using Prisma can pass schema.prisma instead to preserve model and relation names. Translating a Postgres schema covers table, column and constraint mappings, and Translating a Prisma schema covers Prisma models. The schema below shows the completed file with users, access rules and file attachments wired in.
using extension auth;using extension files;using extension napalm;using future simple_scoping; module default { # Whoever is asking: the identity of the session a call came with. global caller := global ext::auth::ClientTokenIdentity; # The addresses the caller has confirmed, lowercased. global caller_emails := str_lower(( select ext::auth::EmailFactor filter .identity ?= global caller and exists .verified_at ).email); # The caller's sign-in as the old system would know it: its issuer, a space, its subject. global caller_sign_in := (global caller).issuer ++ ' ' ++ (global caller).subject; # 'service' for a service key, set in the endpoint's serviceGlobals. A session can't set it. global role: str; type Person { # Who this is here, once they've signed in. Empty until then. identity: ext::auth::Identity { constraint exclusive; }; # Lowercased. Empty for someone the old system knew only by a provider's account. email: str { constraint exclusive; }; required name: str; # The old system's id for this row, and the sign-ins it knew this person by. Both go when the move is over. old_id: str { constraint exclusive; }; multi old_sign_ins: str; access policy self_can_read_and_change allow select, update using (.identity ?= global caller); access policy unclaimed_goes_to_its_person allow select, update using ( not exists .identity and (((.email in global caller_emails) ?? false) or ((global caller_sign_in in .old_sign_ins) ?? false)) ); # A note can't be read without its owner, so the people on a note see each other. access policy seen_by_people_on_the_same_note allow select using (exists ( select (.<owner[is Note] union .<shared_with[is Note]) filter .owner.identity ?= global caller or ((global caller in .shared_with.identity) ?? false) )); access policy the_move_can_write allow all using (global role ?= 'service'); } type Note { required owner: Person; multi shared_with: Person; required title: str; required body: str; required created: datetime { default := datetime_current(); }; old_id: str { constraint exclusive; }; access policy owner_has_full_access allow all using (.owner.identity ?= global caller); access policy shared_with_can_read allow select using ((global caller in .shared_with.identity) ?? false); access policy the_move_can_write allow all using (global role ?= 'service'); } # A file on a note. Whoever may read the note may have the file. type Attachment extending ext::files::File { required note: Note; # The object's key in the old store, which the import copies it by. old_key: str { constraint exclusive; }; access policy note_owner_has_full_access allow all using (.note.owner.identity ?= global caller); access policy shared_with_can_read allow select using ((global caller in .note.shared_with.identity) ?? false); access policy the_move_can_write allow all using (global role ?= 'service'); }}Move query filters into access rules#
In a traditional Postgres app, the database trusts any client holding the connection string, so application code must pass the current user ID into every query manually.
-- Before: every query carries the check, and one that forgets it shows everyone's notes.select n.id, n.title, n.body, n.created_atfrom notes nwhere n.owner_id = $1 or exists (select 1 from note_shares s where s.note_id = n.id and s.user_id = $1)order by n.created_at desc;In Napalm, you declare those permissions once on the Note type instead of repeating filters in SQL.
Schema access rules
Type-level rules enforce caller permissions across every query, subscription and service key.
Because Note enforces read access in the schema, the deployed query that lists a user’s notes needs no WHERE filter at all.
# The notes the caller owns or was given. The rules decide which: the query doesn't say.select Note { id, title, body, created, is_mine := .owner.identity ?= global caller }order by .created desc- Closed by default
- A type without an access rule returns zero rows to every caller, so forgetting a rule never leaves a new table exposed.
- Verified caller
global callerholds the verified identity from the request’s session token. Because Napalm bindsglobal callerfrom the token, application code cannot spoof another user.- Every surface
- Access rules govern deployed queries, live subscriptions, full-text search and agent tool calls without duplicating checks in middleware.
- Backend service keys
- Service keys receive only the permissions granted to their role in your schema. Even your migration script writes through an explicit policy. Access rules covers the full policy language.
Deploy SQL and ORM queries#
Each SQL query or ORM call in your app becomes a named .edgeql file in dbschema/queries. Every write executes as one atomic statement with access rules compiled directly into the SQL.
# A note of the caller's own. Someone with no person yet has no owner to give it, and it's refused.insert Note { owner := assert_exists(assert_single((select Person filter .identity ?= global caller))), title := <str>$title, body := <str>$body,}napalm queries push notesnapalm generate notes --deployed --lang ts -o src/napalm- Nested shapes
- A single query fetches a note alongside its owner and shared recipients without manual SQL joins or N+1 round trips.
- Atomic statements
- Each request runs one statement that commits atomically. Multi-step
BEGINandCOMMITblocks become a single EdgeQL statement mutating multiple linked types. - Typed SDK calls
napalm generateemits a typed client function for every query across eight languages and replaces both your ORM client and thin database-wrapper endpoints.- Functions and triggers
- Scalar SQL functions become EdgeQL queries or schema functions, consistency triggers become constraints or computed properties, and side-effect triggers become jobs queued in the same commit.
Import existing rows#
The export script (scripts/from-postgres.ts) pages through each SQL table in primary-key order and passes rows to the batch sender in Switching over so every request stays within the payload limit.
// scripts/from-postgres.tsimport pg from 'pg'import { move } from './send' const old = new pg.Client({ connectionString: process.env.OLD_DATABASE_URL }) /** A table's rows in the order of their ids, a thousand at a time, so nothing large is held or locked. */async function* pages(sql: string) { let after = '' for (;;) { const { rows } = await old.query(sql, [after]) if (rows.length === 0) return yield* rows after = rows[rows.length - 1].id }} await old.connect()// People first: a note names its owner.await move( 'importPeople', pages(` select id::text, email, name, '{}'::text[] as sign_ins from users where id::text > $1 order by id::text limit 1000`),)await move( 'importNotes', pages(` select n.id::text, n.owner_id::text, n.title, n.body, n.created_at, coalesce(array_agg(s.user_id::text) filter (where s.user_id is not null), '{}') as shared_with from notes n left join note_shares s on s.note_id = n.id where n.id::text > $1 group by n.id order by n.id::text limit 1000`),)await old.end()npm install pg tsxOLD_DATABASE_URL=postgres://… NAPALM_URL=https://<project-address>/branches/rehearsal NAPALM_KEY=ndb_… \ npx tsx scripts/from-postgres.tsEach SQL SELECT aliases columns to match the JSON keys expected by the EdgeQL import statement. The notes query aggregates note_shares rows into an array of user IDs to populate the shared_with multi link.
Migrate users and files#
- Users
- Leave
password_hashbehind, since Napalm does not import external password hashes. Import each user as aPersonrecord with their email address so returning users confirm their email once and reclaim every owned note. Moving your users builds that claim flow. - Files
- Columns storing S3 object keys become
ext::files::Filerecords referencing those keys, and Napalm copies the underlying bytes directly from your bucket. Switching over shows the import command.
Check the migration#
Push schema and queries to the branch
napalm schema push notes --branch rehearsalpreviews and applies the schema migration, andnapalm queries push notes --branch rehearsalcompiles every query file against that branch.Run the export script twice
Both runs print identical counts because the import statements upsert by
old_id, and branch row counts match your Postgres tables.Verify reach for two users
Run
napalm people reachfor a note’s owner and for a shared collaborator. The owner has full read and write access, while the collaborator can read only that shared note.Sign in as a new user
Calling
myNotesreturns zero rows even though the query has nofilterclause, because the schema’s access rules filter unreadable rows automatically.