Skip to the page

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.

Terminal
# 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.sql

A 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.

old-schema.sql
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.

dbschema/default.gel
# 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.

dbschema/default.gel
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)  ));}
PostgresIn the draftNote
create table taskstype TaskNoteThe type takes the table’s name in the singular.
project_id uuid not null references projectsrequired project: ProjectNoteThe link drops _id from the column’s name. A not null column makes the link required.
on delete cascadeon target delete delete sourceNoteDeleting the target still deletes the row.
A unique foreign keyconstraint exclusiveNoteThe link becomes one-to-one.
project_membersmulti members: UserNoteA join table becomes a link to many. Extra columns become properties of the link.
id … primary keyold_id: strNoteNapalm 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.

PostgresIn the draftNote
text, varchar(n)strNoteA length limit is constraint max_len_value(n).
integer, bigint, smallintint32, int64, int16Note
numericdecimalNote
real, double precisionfloat32, float64Note
booleanboolNote
timestamptzdatetimeNote
timestamp, date, timecal::local_datetime, cal::local_date, cal::local_timeNoteA time with no zone stays zoneless.
intervaldurationNote
jsonb, jsonjsonNote
byteabytesNoteA file belongs in a file type.
uuiduuidNoteEvery object already has an id. Use uuid for other ids you store.
text[]array<str>Note
create type … as enumscalar type Status extending enum<Draft, Sent>Note
serial, identityscalar type InvoiceNumber extending sequenceNoteUse a sequence only for a number people see. Ids are uuids.
not nullrequiredNote
uniqueconstraint exclusiveNoteA 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 indexindex 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, timetz or interval column 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_type column beside commentable_id points at several tables. The note names the link and the abstract type to write.
Soft deletes
A deleted_at column 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.

Type a word or two to search every docs page.