Migrating · Schema translation
Translating a Postgres schema
Draft a Napalm schema from the file pg_dump --schema-only writes. Tables become types, foreign keys become links and each policy becomes a closed rule.
- API
- —
- In the schema
- —
The command#
Dump the old database’s tables with pg_dump --schema-only, then draft from the dump. The dump holds the tables, keys, triggers and policies but no rows.
SQL DDL to default.gel
napalm schema draft --from old-schema.sql converts CREATE TABLE statements, CHECK enums, tsvector columns and RLS policies without connecting to Postgres.
Typed object types & links
Tables become object types, references foreign keys become direct object links and primary keys carry over in old_id while the move runs.
# Dump the old database's tables to one filepg_dump --schema-only --no-owner "$OLD_DATABASE_URL" > old-schema.sql # Write a first schema to dbschema/default.gelnapalm schema draft --from old-schema.sqlA Supabase database drafts the same way from supabase db dump. Coming from Supabase has the command.
A sample project#
Here is a small project tracker as Postgres tables. Four tables hold users, projects, tasks and the members of each project. A trigger keeps updated_at current, and one policy guards the 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());The command writes three types from the four tables.
# 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 shared type, the reverse links, the rewrite, the enum and the search index follow the rules under Additions in every draft. The policy becomes a closed rule, as Closed access rules explains.
Tables, columns and keys#
Each table becomes a type. Columns become properties, and foreign keys become links to the other type.
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) ));}| Postgres | In the draft | Note |
|---|---|---|
create table tasks | type Task | NoteThe type takes the table’s name in the singular. |
project_id uuid not null references projects | required project: Project | NoteThe link drops _id from the column’s name. A not null column makes the link required. |
on delete cascade | on target delete delete source | NoteDeleting the target still deletes the row. |
A unique foreign key | constraint exclusive | NoteThe link becomes one-to-one. |
project_members | multi members: User | NoteA join table becomes a link to many. Extra columns become properties of the link. |
id … primary key | old_id: str | NoteNapalm gives every object a new id. old_id keeps the old key while the move runs. |
Column types and constraints#
An automated test verifies the draft command against every row in the table below.
| Postgres | In the draft | Note |
|---|---|---|
text, varchar(n) | str | NoteA length limit is 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 | NoteA time with no zone stays zoneless. |
interval | duration | Note |
jsonb, json | json | Note |
bytea | bytes | NoteA file belongs in a file type. |
uuid | uuid | NoteEvery object already has an id. Use uuid for other ids you store. |
text[] | array<str> | Note |
create type … as enum | scalar type Status extending enum<Draft, Sent> | Note |
serial, identity | scalar type InvoiceNumber extending sequence | NoteUse a sequence only for a number people see. Ids are uuids. |
not null | required | Note |
unique | constraint exclusive | NoteA unique pair of columns becomes constraint exclusive on ((.a, .b)). |
check (…) | constraint expression on (…) | NoteA plain bound becomes a built-in constraint, such as constraint min_value(0). |
default now() | default := datetime_current() | Note |
create index | index on (.created) | NoteLinks and exclusive properties are indexed already. |
Untranslated items#
A comment that starts with draft: marks each item below. Password hashes and vectors also stay notes, as Untranslated items explains.
- Column types
- A
money,citext,timetzorintervalcolumn takes the closest type, and a note describes the change. A type with no match stays a note. - Generated columns
- A generated column stays a note with the expression. Write the expression in EdgeQL as a computed property.
- Views and functions
- A view becomes a query in Napalm, and so does a function that computed a value.
- Other triggers
- A trigger with a condition stays a note, and so does a trigger whose function does more than set the time.
- Polymorphic pairs
- A
commentable_typecolumn besidecommentable_idpoints at several tables. The note names the link and the abstract type to write. - Soft deletes
- A
deleted_atcolumn in a view’s filter gets a note. An alias or an access rule hides those rows in Napalm. - Other checks
- A check with a plain bound becomes a ready constraint. Any other check stays a note with the SQL.
- Other indexes
- A partial index, an expression index or an index other than a B-tree or a hash stays a note with the SQL.