Migrating · Schema translation
Translating a Postgres schema
Draft a Napalm schema from a pg_dump --schema-only file. Tables become object types, foreign keys become links and RLS policies translate into access rules.
- API
- —
- In the schema
- —
Running schema draft#
Export your Postgres schema with pg_dump --schema-only, then pass the SQL file to napalm schema draft. The dump captures tables, keys, triggers and RLS policies without exporting any row data.
# Export table, constraint and policy definitions without row datapg_dump --schema-only --no-owner "$OLD_DATABASE_URL" > old-schema.sql # Generate an initial schema in dbschema/default.gelnapalm schema draft --from old-schema.sqlSupabase projects translate the same way from supabase db dump. Coming from Supabase shows the full workflow.
Offline dump parsing
The CLI converts SQL tables, constraints and policies without a database connection.
Types and object links
Foreign keys and join tables turn into typed single and multi links.
Example project tracker#
The SQL schema below models a small project tracker across four tables: users, projects, tasks and project memberships. A trigger updates updated_at on writes, and one RLS policy guards projects.
create table users ( id uuid primary key default gen_random_uuid(), email text unique not null, password_hash text not null, role text not null default 'member' check (role in ('member', 'admin')), created_at timestamptz not null default now(), updated_at timestamptz not null default now());create table projects ( id uuid primary key default gen_random_uuid(), owner_id uuid not null references users (id), name text not null, created_at timestamptz not null default now(), updated_at timestamptz not null default now());create table tasks ( id bigserial primary key, project_id uuid not null references projects (id) on delete cascade, title text not null, notes text, search tsvector generated always as (to_tsvector('english', title || ' ' || coalesce(notes, ''))) stored, created_at timestamptz not null default now(), updated_at timestamptz not null default now());create table project_members ( project_id uuid not null references projects (id) on delete cascade, user_id uuid not null references users (id), primary key (project_id, user_id));create index tasks_search_idx on tasks using gin (search); create function touch_updated_at() returns trigger language plpgsql as $$begin new.updated_at = now(); return new;end;$$;create trigger users_touch before update on users for each row execute function touch_updated_at();create trigger projects_touch before update on projects for each row execute function touch_updated_at();create trigger tasks_touch before update on tasks for each row execute function touch_updated_at(); alter table projects enable row level security;create policy owners on projects for all using (owner_id = auth.uid());napalm schema draft produces three object types from those four tables and collapses project_members into a multi link.
# This first schema was drafted from old-schema.sql by napalm schema draft. Read every line, then check the schema on a# branch with napalm schema push <project> --branch <branch> --plan.## Each table is a type, and each foreign key is a link. A join table is a multi link. Each link has a computed link back# on the target type. Three or more types that share properties extend one abstract type. old_id keeps each row's old# key for the move. A type with no access rule answers nothing. Each policy from the old tables is a comment above a# rule that allows nothing. A comment that starts with draft: marks an item the draft couldn't translate. using extension napalm;using future simple_scoping; module default { # The values the users.role check allowed. scalar type UserRole extending enum<member, admin>; # The properties User, Project and Task share. abstract type Timestamped { required created_at: datetime { default := datetime_current(); }; required updated_at: datetime { default := datetime_current(); rewrite update using (datetime_of_statement()); }; } type User extending Timestamped { required email: str { constraint exclusive; }; # draft: password_hash stays behind, because a project can't take another system's password hashes. The guide at # https://napalmdata.com/developers/migrating/moving-users gives people their rows back. required role: UserRole { default := <UserRole>'member'; }; old_id: str { constraint exclusive; }; # The other side of each link to User. projects_as_owner := .<owner[is Project]; projects_as_members := .<members[is Project]; } type Project extending Timestamped { required owner: User; required name: str; # Stored in the project_members table. multi members: User; old_id: str { constraint exclusive; }; # The other side of each link to Project. tasks := .<project[is Task]; # draft: the policy "owners" (FOR ALL) became the rule below. The rule allows nothing until you write the condition: # using (owner_id = auth.uid()) # In EdgeQL, the condition is (.owner.identity ?= global caller). That condition needs a caller global and an # identity link on the people type, and the guide at https://napalmdata.com/developers/migrating/moving-users builds # both. access policy owners allow all using (false); } type Task extending Timestamped { required project: Project { on target delete delete source; }; required title: str; notes: str; # draft: the search column was a generated tsvector over title and notes. The fts::index below indexes the same # text. old_id: str { constraint exclusive; }; index fts::index on (( fts::with_options(.title, language := fts::Language.eng), fts::with_options(.notes, language := fts::Language.eng) )); }}The abstract base type, reverse links, timestamp rewrite, enum and full-text search index follow the rules in Generated schema constructs. Closed access rules covers how the RLS policy becomes a closed scaffold.
Tables, columns and keys#
Each table becomes an object type, columns become properties and foreign keys become typed links.
type Task extending Timestamped { required project: Project { on target delete delete source; }; required title: str; notes: str; # draft: the search column was a generated tsvector over title and notes. The fts::index below indexes the same # text. old_id: str { constraint exclusive; }; index fts::index on (( fts::with_options(.title, language := fts::Language.eng), fts::with_options(.notes, language := fts::Language.eng) ));}The table below maps each Postgres table and key declaration to its drafted EdgeQL equivalent.
| Postgres | In the draft | Note |
|---|---|---|
create table tasks | type Task | NoteUses the singular PascalCase form of the table name. |
project_id uuid not null references projects | required project: Project | NoteStrips _id from the column name, and not null marks the link required. |
on delete cascade | on target delete delete source | NoteDeleting the target object deletes referencing rows. |
A unique foreign key | constraint exclusive | NoteEnforces a one-to-one link. |
project_members | multi members: User | NoteCollapses a join table into a multi link and turns extra columns into link properties. |
id … primary key | old_id: str | NoteNapalm assigns every object a new id and preserves the original primary key in old_id during migration. |
Column types and constraints#
Automated tests verify napalm schema draft against every Postgres type and constraint in the table below.
| Postgres | In the draft | Note |
|---|---|---|
text, varchar(n) | str | NoteCharacter limits become constraint max_len_value(n). |
integer, bigint, smallint | int32, int64, int16 | Note |
numeric | decimal | Note |
real, double precision | float32, float64 | Note |
boolean | bool | Note |
timestamptz | datetime | Note |
timestamp, date, time | cal::local_datetime, cal::local_date, cal::local_time | NoteTimestamps without time zones map to local calendar types. |
interval | duration | Note |
jsonb, json | json | Note |
bytea | bytes | NoteUse an ext::files::File type for stored files instead of inline bytes. |
uuid | uuid | NoteEvery object already has an id property, so reserve uuid properties for external identifiers. |
text[] | array<str> | Note |
create type … as enum | scalar type Status extending enum<Draft, Sent> | Note |
serial, identity | scalar type InvoiceNumber extending sequence | NoteReserve sequences for display numbers such as invoice numbers, since object id values are UUIDs. |
not null | required | Note |
unique | constraint exclusive | NoteComposite unique constraints become constraint exclusive on ((.a, .b)). |
check (…) | constraint expression on (…) | NoteSimple numeric bounds become built-in constraints such as constraint min_value(0). |
default now() | default := datetime_current() | Note |
create index | index on (.created) | NoteLinks and exclusive properties carry automatic indexes already. |
Untranslated items#
The command marks each untranslated Postgres construct below with a # draft: comment. Untranslated items covers password hash and vector columns, which emit notes across all sources.
- Column types
- Columns using
money,citext,timetzorintervalmap to the closest scalar type alongside an explanatory note. Unrecognized types emit a# draft:comment. - Generated columns
- Generated columns emit a note with the original SQL expression so you can rewrite it as a computed EdgeQL property.
- Views and functions
- SQL views and scalar functions emit notes and map to deployed EdgeQL queries or schema functions.
- Complex triggers
- Conditional triggers and trigger functions that do more than stamp
updated_atemit# draft:notes. - Polymorphic pairs
- Paired columns like
commentable_typeandcommentable_idemit a note suggesting a link to a shared abstract base type. - Soft deletes
- Views that filter on
deleted_atemit a note. In Napalm, schema aliases or access rules hide soft-deleted rows. - General CHECK rules
- Simple numeric bounds become built-in constraints, while general SQL
CHECKexpressions stay in a comment for manual translation. - Specialized indexes
- Partial indexes, expression indexes and index access methods beyond B-tree or hash emit a
# draft:comment with the original SQL.