Migrating · Platform guides
Coming from Postgres
Turn tables into types, the checks in your queries into rules and ORM calls into deployed queries. Then move the rows with a script.
- API
- —
- In the schema
ext::auth::Identity
What you’ll move#
A notes app on Postgres: a users table with password hashes, notes that belong to a user and a join table for the notes shared with others. The app reaches the database through an ORM or hand-written SQL. Every query carries a WHERE clause filtering rows by user.
In Napalm the tables are types, the join table is a link and that WHERE is a rule on the type. The rows come over with a script. Coming from Supabase? Supabase’s auth, storage and policies have a separate page.
-- 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#
You need a project created in the console and the napalm CLI signed in. Work on a branch until you have rehearsed the full move.
# The old database's tables, to write the schema frompg_dump --schema-only --no-owner "$OLD_DATABASE_URL" > old-schema.sql # A first schema, drafted from that file into dbschema/default.gelnapalm schema draft --from old-schema.sql # Or, for an app on Prisma, from its schemanapalm schema draft --from prisma/schema.prisma # A branch to work on, and the schema and queries checked against itnapalm branches create notes rehearsalnapalm schema push notes --branch rehearsalnapalm queries push notes --branch rehearsalA project exposes no SQL port and no connection string, so psql, an ORM and a pooler cannot connect. The app calls deployed queries over HTTPS instead. Each section below turns one piece of the old app into its Napalm counterpart. A coding agent can handle most of the conversion, and Moving with a coding agent lists the exact files to provide.
Turn tables into types#
Each table becomes a type and each column a property. A foreign key becomes a link to the target type, and a join table disappears into a link to many. Every row gets a new id while keeping its old id for as long as the move runs.
Tables and join tables become types and links
napalm schema draft turns your SQL dump or Prisma schema into dbschema/default.gel, replacing join tables with multi-links.
napalm schema draft writes the first draft of the schema from old-schema.sql. An app on Prisma can draft from schema.prisma instead to preserve model and relation names. Translating a Postgres schema shows how the command converts each table, column type and constraint, and Translating a Prisma schema covers Prisma. The schema below is the finished file with people, rules and files 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'); }}Put your code’s checks into rules#
In the old app, the database trusted any client holding a connection, so the app passed the caller’s identity into every query by hand.
Access rules replace per-query WHERE checks
Rules live once on the type and enforce global caller across every query, live query, search and service key.
-- 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, the check lives once on the type, as shown in the two rules on Note above. The query that lists a person’s notes never repeats the access check.
# 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 with no rule answers nothing to anyone, so a forgotten rule can never leave a new type open.
- The caller
global calleris the verified identity of the request’s session. The project reads it from the token, so the app cannot pass another caller.- Every kind of call
- A rule holds across deployed queries, live queries, search and agent calls alike. You never duplicate the check in a second layer.
- Your backend too
- A service key receives only the access a rule grants its role. The move itself writes that way. Access rules covers the full language.
Turn SQL and ORM calls into deployed queries#
Each query the app makes becomes a file in dbschema/queries, named for what it does. Every write runs as one atomic statement with the access check compiled inside.
# 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 results
- A query selects a note, its owner and its share list in one shape without manual joins or N+1 queries.
- One statement
- Each request runs one statement that commits whole or not at all. Work that needed
BEGINandCOMMITaround several statements becomes one statement touching several types. - Typed calls
napalm generateemits a typed call for each query in eight languages. You drop the ORM client and the API layer that only existed to keep the database off the internet.- Functions and triggers
- A SQL function that computed a result becomes a query. A trigger that kept a column consistent becomes a constraint or computed property. A trigger that called another service becomes a job queued in the same commit.
Move the rows#
The reader pages through each table in id order and hands rows to the move’s sender, which batches them under the project’s request limit. Switching over has the sender and the import statements it calls.
// 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.tsThe column names in each select are the keys the import statement reads, so any column renamed in the schema takes its new name here. Each note carries its share rows as an array, which becomes the link replacing the join table.
Bring people and files#
- People
- The
password_hashcolumn stays behind because a project cannot import another system’s hashes. Each user arrives as aPersonwith their email address. At first sign-in, they confirm the address and reclaim every owned note. Moving your users builds that flow. - Files
- A column holding an object key becomes a file type storing that key, and Napalm copies the bytes from your bucket. Switching over has the command.
Check the move#
Push the schema to the branch
napalm schema push notes --branch rehearsalshows and applies the plan.napalm queries push notes --branch rehearsalcompiles every query file against the branch’s schema.Run the reader twice
Both runs print identical row counts, and after each run the project’s counts match the old database.
Read as two people
Run
napalm people reachfor a note’s owner and for someone on its share list. The owner can modify the note, while the shared user can read only that note and none of the owner’s other notes.Sign in as someone new
myNoteshas no filter and still returns zero rows because the access rules filter unreadable notes automatically.