Learn · Schema & access
Schema
Your whole data model and the access rules live in one file, dbschema/default.gel. Run napalm schema push to migrate the data model.
- In the schema
ext::napalm::root
Single schema file#
dbschema/default.gel declares enums, caller globals, object types, links, computed backlinks, mutation rewrites and access policies in one declarative file. Check the file into version control alongside your application code. The collaborative notes app used throughout these guides runs on this single schema.
Single declarative schema file
Object types, typed links, constraints, mutation rewrites, access policy rules and ext::napalm::root placement annotations compile together from dbschema/default.gel.
using extension auth;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; scalar type Visibility extending enum<Private, Team, Public>; type Person { # Not required: a caller reads their own identity alone, so another person's reads as empty. identity: ext::auth::Identity { constraint exclusive; }; required name: str { constraint max_len_value(80); }; notes := .<author[is Note]; note_count := count(.notes); access policy self_has_full_access allow all using (.identity ?= global caller); access policy signed_in_can_read allow select using (exists global caller); } type Note { required title: str; body: str; multi tags: str; required visibility: Visibility { default := Visibility.Private; }; required author: Person { default := (select Person filter .identity = global caller); }; required created: datetime { default := datetime_of_statement(); readonly := true; }; updated: datetime { rewrite insert, update using (datetime_of_statement()); }; constraint exclusive on ((.author, .title)); index on (.created); access policy author_has_full_access allow all using (.author.identity ?= global caller); access policy public_can_read allow select using (.visibility = Visibility.Public); }}Object types and properties#
Each type defines a stored table of objects with an automatic id: uuid primary key. Marking a property required guarantees every record holds a value. Properties without required are optional, and EdgeQL represents an absent value as the empty set {} rather than SQL NULL.
Stored record with UUID key and typed properties
Every stored type compiles to a PostgreSQL table of typed records with an id: uuid primary key, strict scalar properties and empty-set {} optionals instead of SQL NULL.
| Scalar type | Description |
|---|---|
str | UTF-8 string |
bool | Boolean (true or false) |
int16, int32, int64, bigint | Signed integers (bigint has arbitrary precision) |
float32, float64, decimal | IEEE 754 floats and arbitrary-precision exact decimal |
datetime, duration, cal::* | Timezone-aware timestamps, durations and local calendar dates and times |
uuid, bytes, json | UUIDs, raw byte arrays and structured JSON values |
enum<…> | Typed enumeration of named variants (such as Visibility above) |
Prefixing a property with multi (for example, multi tags: str) stores an unordered set of unique values. Properties can also use composite array<T>, tuple<…> and range<T> types.
Typed links#
Typed links declare relationships between object types directly without manual foreign-key columns or join tables. A single link (the default) points to one target record, while a multi link points to a set of target records.
Linked record graph
Typed single and multi links wire stored records directly across parent and child types without manual foreign-key columns or join tables.
required author: Person { default := (select Person filter .identity = global caller);};Computed fields and backlinks#
A property or link defined with := evaluates dynamically at query time. Backlink syntax (.<author[is Note]) traverses a link in reverse, resolving every Note whose author points to the current Person.
Read-time computed fields and reverse backlinks
Derived := expressions and .<author[is Note] backlinks evaluate live inside the read snapshot with zero denormalized counters or join tables to keep in sync.
notes := .<author[is Note];note_count := count(.notes);Computed fields behave identically to stored fields across application queries and access policies, with no counters or join tables to keep in sync.
Constraints, defaults and rewrites#
Constraints, defaults and rewrite hooks enforce domain invariants inside the PostgreSQL transaction on every write, regardless of which deployed query, action or service key mutates the row.
In-transaction mutation rewrites and constraints
rewrite insert, update hooks stamp fields such as datetime_of_statement() inside the SQL write before constraint checks and write policies validate the row.
constraint exclusive- Enforces uniqueness on a single field or composite tuple expression (such as
constraint exclusive on ((.author, .title))). max_len_value- Enforces a built-in maximum length. Other constraints include
min_value,max_value,regexp,one_ofand customconstraint expression on (...)checks. default- Fills an omitted field on
insert. Defaults can read schema globals such asglobal caller. readonly- Allows setting the field on
insertand rejects any subsequentupdateto that field. rewrite- Runs a schema-enforced mutation hook (
rewrite insert, update using (...)) inside the transaction before constraints and policies check the row, which works well for audit timestamps. index on- Builds a B-tree or expression index in PostgreSQL to accelerate filters, sorts and policy joins.
Access policies and globals#
Access policies live directly inside each object type and walk the record’s properties, links, computed fields and request globals such as global caller in the same algebra as queries.
access policy author_has_full_access allow all using (.author.identity ?= global caller);access policy public_can_read allow select using (.visibility = Visibility.Public);Every stored object type without an access policy is closed over the API by default. See Access and sign-in for policy design patterns and auditing tools.
Commit notifications#
Add a notify declaration inside an object type to emit durable webhook deliveries whenever a committed transaction inserts, updates or deletes matching rows. Notifications fire strictly at commit, so rolled-back writes and is_dry_run previews never trigger outbound webhooks.
type Note { required author: Person; required title: str; notify note_changed after insert, update, delete;}Subscribe HTTPS endpoints with napalm webhooks add, the console or the Control API. Each webhook delivers either a compact ping summary (event name, affected types, roots, row counts and commit bookmark) or access-policy-filtered rows read from your cluster’s durable change log. See webhooks in the TypeScript SDK for signature verification and causal bookmark handoff.
Migrations#
After editing dbschema/default.gel, run napalm schema push. The server diffs your local SDL against the target branch, plans the DDL statements, verifies statically that every deployed query still compiles and previews the plan before applying the migration in one transaction.
- New required fields
- A
requiredfield added to an existing type needs adefaultor afilldecision to give existing objects a value. Afilldecision also makes an optional field required in one push. The decisions live indbschema/decisions.yamlbeside the schema. - Guessed renames
- A rename the engine guesses at stops the push until
dbschema/decisions.yamlanswersrenameorreplace. At a terminal the push asks and offers to write the file. - Destructive drops
- Removing a type, property or link permanently drops the stored column or table. The CLI highlights drops and asks for confirmation.
- Deployed query safety
- A push that would break any deployed query on the project fails before touching the database.
- Idempotent pushes
napalm schema pushexits cleanly with no changes when the branch schema already matches your local file.
For full SDL syntax details, see the upstream Gel reference covering object types, links, computed fields, constraints, globals and mutation rewrites.
Branches and pull requests#
A branch is a separate database beside main that starts with main’s schema. Push a migration to a branch with --branch to test schema and query changes without touching main.
A project that follows a GitHub repository gets a branch for each pull request, and the pull request shows the migration plan. Branches covers each branch’s address, keys and sessions, copies of main’s rows, pull request branches and removal.
Placement roots and sharding#
Roots in Napalm are places, not walls. The compiler infers multi-tenant shard roots by walking required single stored links upward from child types to top-level owner types. When Task links to Project, Project links to Workspace and Workspace links to Organization, the compiler traces .project.workspace.org and classifies Organization as the placement root for all four types. Every table keeps a standard id: uuid primary key and clean object links without tenant_id columns or composite foreign keys.
Compiler-inferred tenant root trees
Walking required single owner links upward co-locates Organization, Workspace, Project and Task on one shard while keeping standard id: uuid primary keys.
| Classification | Compiler rule | Example types |
|---|---|---|
root | Has no outbound required single link to a non-reference project type and owns at least one rooted child type, or declares ext::napalm::root := 'root'. | Example typesOrganization, Person |
rooted | Reaches one root type unambiguously through a chain of required single owner links. | Example typesWorkspace, Project, Task |
reference | Lookup table marked ext::napalm::root := 'reference'. Every shard keeps a local copy updated in one atomic commit. | Example typesBillingPlan |
unassigned | Standalone project type with no outbound owner link, no rooted child types and no root or reference annotation. | Example types— |
shared | Reaches multiple roots, reaches one root by distinct unproven paths or sits in a required link cycle. Rows stay on the base shard. | Example types— |
Disambiguating types with multiple required links#
Links targeting std::* or ext::* types (such as ext::auth::Identity), multi links, computed links and links to reference types never compete as owner links. When an object type declares two or more required single stored links to non-reference project types (for example, Task.project reaching Organization and Task.author reaching Person), the compiler settles ownership deterministically.
- Equality proof
- An unconditional
constraint expressionequating two required link paths (such asconstraint expression on (.project.workspace.org = .author.org)) proves both paths reach the same root object. The compiler canonicalizes the longer path to the shorter path. - Compiler tie-breaking
- Without an annotation or equality proof, the compiler picks one owner link in fixed priority order: cascading containment (
on target delete delete source), an owner link inherited from a base type, an immutable link (readonly := true), the deepest link path to a root (Task.project.workspace.orgat three hops ahead of a one-hop link) and finally the first link name in alphabetical order. Remaining links stay ordinary cross-root references.
Placement annotations and owner link mutability#
Declare annotation ext::napalm::root on an object type or link when your domain calls for a different ownership boundary than automatic tie-breaking. Annotations inherit across subtypes and overloaded links.
Explicit root and owner-link annotations
Declare ext::napalm::root on an object type ('root', 'reference') or link ('owner', 'none') to set shard co-location boundaries explicitly.
using extension auth;using extension napalm;using future simple_scoping; module default { type BillingPlan { annotation ext::napalm::root := 'reference'; required slug: str { constraint exclusive; }; } type Person { annotation ext::napalm::root := 'root'; required identity: ext::auth::Identity { constraint exclusive; }; } type Organization { required name: str; required plan: BillingPlan; } type Workspace { required org: Organization { readonly := true; on target delete delete source; }; required name: str; } type Project { required workspace: Workspace { readonly := true; on target delete delete source; }; required name: str; } type Task { required project: Project { annotation ext::napalm::root := 'owner'; on target delete delete source; }; required author: Person { annotation ext::napalm::root := 'none'; }; required title: str; }}| Target | Annotation | Compiler and runtime behavior |
|---|---|---|
| Object type | ext::napalm::root := 'root' | Compiler and runtime behaviorMarks the object type as an explicit top-level placement root even when outbound required links exist. |
| Object type | ext::napalm::root := 'reference' | Compiler and runtime behaviorReplicates a low-churn lookup table to every shard in one atomic commit so single-root queries join locally and excludes incoming links from root walks. |
| Link | ext::napalm::root := 'owner' | Compiler and runtime behaviorSelects the single project link that determines shard ownership and sets aside sibling required links. |
| Link | ext::napalm::root := 'none' | Compiler and runtime behaviorExcludes the link from root inference so author, guest or partner references break multi-root ambiguity and ownership cycles. |
Every required single owner chain makes a root placeable once you run napalm placement enable. Marking structural tenant links readonly := true fixes each record under one root permanently and lets engines cache object-to-root lookups for the lifetime of the row. Writable owner links (such as moving Task.project between projects) remain valid. While both roots share a shard, updating the link moves the record and every descendant child row to the new parent root inside the write transaction. Once roots live on different shards, re-parenting a row across shards is refused because moving the subtree would write across two shards.
Compile-time and push-time routing diagnostics#
Run napalm roots <project> or napalm schema push <project> --plan (or call GET /projects/{id}/roots) to inspect inferred root paths, movable links and per-query shard routing before distributing a branch. Invalid ext::napalm::root values fail migration checks with 400 schema_invalid, while placement blockers and cross-root statements appear in the root report.
| Condition | Diagnostic reported by napalm roots and schema push | Resolution |
|---|---|---|
| Invalid annotation value or target | ext::napalm::root on a type is 'root' or 'reference', on a link is 'owner' or 'none', 2 links are marked owner or .<link> is marked owner but is no single link to a type of the project. | ResolutionUse root or reference on object types, and mark at most one single project link owner. |
| Optional link in owner chain | <Type>.<link> keeps <Root> from being placed. | ResolutionMake every link along the owner chain required, or annotate <Type> as root when rows stand alone. |
| Required link cycle | ownership cycle: A.b -> B, B.a -> A (shared on the base shard). | ResolutionAnnotate the non-owning back-reference link with ext::napalm::root := 'none'. |
| Unguarded cross-root read or policy | reads across roots (<Type> is read across roots or reaches 2 roots: …). | ResolutionPin the query filter or every allow policy to one root (filter .project.workspace.org = <Organization>$org or a root global), or add a core copy with napalm core-copies add for cross-tenant reporting. |
| Unguarded cross-root write | writes across roots (<Type> is written unpinned or reaches 2 roots: …). | ResolutionScope every insert, update and delete on rooted types to a single root. Unpinned rooted writes are refused on distributed branches. |
Unscoped constraint exclusive | Uniqueness constraint on a rooted type omits the root path. | ResolutionScope tenant-local uniqueness to the root (such as constraint exclusive on ((.org, .slug))) so writes avoid cross-shard uniqueness checks against the base shard. |
See Shard placement annotations for extension reference details, Horizontal sharding and rebalancing for online bucket moves and core copies and Multi-tenant B2B SaaS for a complete multi-organization guide.