Entities
An entity type is a module that describes one kind of thing your app stores, like a todo, a project or a user: its attributes, its relationships to other entity types, the values it computes from them, and who may read and write it. Hologram builds the database table, the validation and the browser's copy of the data from that one declaration.
Defining an Entity Type
An entity type uses Hologram.Entity and declares its fields with attribute, relationship and derived:
defmodule MyApp.Task do
use Hologram.Entity
attribute :title, :string, min_length: 1, max_length: 200
attribute :status, :enum, values: [:todo, :doing, :done], default: :todo
attribute :due_on, :date, optional: true
relationship :project, MyApp.Project
allow :create
allow :read
allow :update
allow :delete
end
The allow lines say who may do what with the entity type's entities. Nobody may do anything that no line allows, so an entity type without them can't be read or written from a page at all. Access Control covers them, and the other examples on this page leave them out.
Attributes, relationships and derived fields share one set of names, so no two of them can have the same name. A name can't start or end with an underscore or contain two underscores in a row, and the names of the system attributes below are taken.
You don't create the table. In dev, Hologram changes the database to match the entity types, and in production a migration does it. See Migrations.
Attributes
An attribute is a value stored on each entity: attribute name, type, followed by options when it needs any.
Types
:boolean-trueorfalse.:date- aDate.:datetime- aDateTime. It's stored as an instant, so it comes back in UTC whatever time zone it was written in.:enum- one atom out of a fixed list, given with thevaluesoption.:float- a float. An integer is accepted too.:id- the ID of an entity, in the 22-character form IDs below describe. A relationship's_idfield has this type.:integer- an integer that fits in 64 bits.:string- a UTF-8 string with no NUL byte.:time- aTime.:uuid- a UUID from another system, as a lowercase 36-character string. Use:idfor the IDs of your own entities.
Options
attribute :name, :string
attribute :done, :boolean, default: false
attribute :note, :string, optional: true
attribute :slug, :string, unique: true
attribute :priority, :enum, values: [:low, :normal, :high], default: :normal
default- the value the attribute starts with when you don't set it. When you add a required attribute to a type that already has entities, those entities get it too. It has to be a valid value for the attribute, or the build fails.optional- the attribute may benil. Without it, the attribute is required, andDB.createandDB.updaterefuse an entity that leaves itnil. The Validation section below lists the reason they report.unique- no two entities of the type may hold the same value. Anilnever counts as a duplicate, so an optional unique attribute can be left empty on any number of entities. A unique attribute can't have a default, since every entity that left it out would get the same value.values- the atoms an:enumattribute may hold, and it's required for one. Their order is the order that comparisons and sorting use, so with[:low, :normal, :high],:lowsorts first.
The browser can't see other users' entities, so only the server can tell that a value is already taken. A write in the browser goes ahead, and the server refuses it if the value is taken by the time it arrives. The browser then undoes the write. Writing Data covers what happens to the rest of the write.
When a value is likely to be taken, like a username someone picks at sign-up, write it in a command instead. The command runs on the server, so it learns at once whether the value is free, and the page can show the answer before the user moves on. The write then needs a connection, so it doesn't work offline.
A unique string is limited to 2,692 bytes, so that it fits in its index. DB.create and DB.update refuse a longer one.
Validation Options
These options limit the values an attribute accepts:
attribute :rating, :integer, in: 1..5
attribute :stock, :integer, min: 0
attribute :price, :float, min: 0.0
attribute :opens_at, :time, min: ~T[06:00:00], max: ~T[12:00:00]
attribute :code, :string, length: 6
attribute :username, :string, min_length: 3, max_length: 30, format: ~r/^[a-z0-9_]+$/
minandmax- the smallest and the largest value, for:integer,:float,:date,:datetimeand:time.in- a range the value has to fall in, for:integer.length,min_lengthandmax_length- the exact, the smallest and the largest length of a:string. Length counts characters (Unicode code points), not bytes.format- a regex a:stringhas to match.
Hologram checks the options when it compiles the entity type. An option the type doesn't take, a min larger than its max or a default that breaks one of the rules fails the build with an error that names the attribute.
Server-Only Attributes
An attribute with server_only: true never reaches the browser:
attribute :api_token, :string, optional: true, server_only: true
Server code reads and writes it like any other attribute. In the browser, the field always holds a %Hologram.Entity.ServerOnly{} struct instead of the value, and browser code can't write it. Set it in a command or a job. A query run in the browser, or a derived field, can't filter or sort on it either, since that would give the value away.
Hologram removes server-only values from the entities it sends to the browser, on its own. That covers the HTML the server renders, page and component state, props, context, and every entity the data layer syncs: wherever such a value would leave the server, Hologram puts %ServerOnly{} in its place. So in the browser, and in any template, even one rendered on the server, a server-only attribute holds %ServerOnly{}.
This works on entities. A value you copy out of one, like put_state(component, :token, user.api_token), is a plain value, and Hologram sends it to the browser like any other. Keep server-only values in server code, and put the entity in state, not the value.
Your server code works with the real value. An entity that init/3, a command or a job reads through DB holds it, and you don't need to remove it yourself before putting the entity in state or passing it as a prop. A prop holds %ServerOnly{} in a component's init/3 too, so when init/3 needs the real value, read the entity through DB. A prop's default: and the props a page's layout line spells out hold %ServerOnly{} too.
While a template or a derived function runs, or the to_string/1 of a value a template prints, DB hides server-only values on the server too, in processes the template starts as well:
DB.readreturns%ServerOnly{}in their place, and raises aHologram.MisuseErrorfor a query that filters or sorts on a server-only attribute, even a trusted one.DB.createandJob.createreturn%ServerOnly{}in their place.DB.sqlraises aHologram.MisuseError.
Hologram can't hide a value in these cases:
- A struct a template builds itself, with
Task.newor%Task{}, holds the declared defaults on the server, and the HTML shows them when the template prints them. - A trusted read in a process that was already running, or in a
Task.Supervisortask, returns the real values, unless the template wraps the function withHologram.Auth.as_current_user. - The result of a write made in a template can give a value away, like an error saying that it's taken or that a number passes its bound.
can?on the server checks the stored values, and a read rule that checks a server-only attribute shows what it found through the entities a read returns.
A server-only attribute can have a default, and the default stays on the server too:
attribute :flagged, :boolean, default: false, server_only: true
A struct built in the browser, with Task.new or %Task{}, holds %ServerOnly{} in every server-only attribute, whether it declares a default or not. When an action creates the entity, the server fills in the default. The attribute's validation options stay on the server as well, so the browser doesn't validate it, and only the server can refuse a required one that has no default.
The same goes for a command that creates an entity built in the browser. For DB.create, %ServerOnly{} in a server-only attribute means that nobody set it, so it writes the default, or nil when there's none. To write something else, the command sets the field itself:
def command(:create_task, %{task: task}, server) do
DB.create!(task)
server
end
def command(:create_flagged_task, %{task: task}, server) do
DB.create!(%{task | flagged: true})
server
end
For a task your page sends, the first command creates a task with flagged set to false, the second with true. Command params come from the browser, and a user can change them. %ServerOnly{} is what your own pages send, but a user can send a real value in its place, and DB.create saves it. When users mustn't choose the value, set it in the command, even if it's the same as the default:
DB.create!(%{task | flagged: false})
The browser can't copy a server-only value. If an action duplicates a task whose flagged is true, the new task gets the default, false. To keep the value, duplicate the task in a command, where DB.read returns the real one:
def command(:duplicate_task, %{id: id}, server) do
task = DB.read(Task, id)
DB.create!(
Task.new(title: task.title, project_id: task.project_id, flagged: task.flagged)
)
server
end
Only a create takes %ServerOnly{}, and only in a server-only attribute. An update that names a server-only attribute with it raises a Hologram.MisuseError, and so does a create or an update that writes it to any other attribute or to a relationship's _id field. Updating another field of an entity that holds it is fine.
To tell the struct from a value, call server_only?/1, which pages and components import. It works on the server and in the browser. In a template:
{%if server_only?(@user.api_token)}
<p>Token hidden</p>
{/if}
Matching on the struct alone works too, in a case or a function head in browser code. Its fields are internal and may change:
alias Hologram.Entity.ServerOnly
case user.api_token do
%ServerOnly{} -> :hidden
token -> token
end
No query sends a server-only attribute to the browser, so include doesn't help here. It loads a field that holds a NotIncluded struct, which Relationships covers below.
DB.sql returns raw rows, server-only columns included, so code that sends its results to the browser has to leave them out itself. That's why it raises in a template or a derived function.
System Attributes
Hologram adds these attributes to every entity type and sets them itself:
id- the entity's ID.created_atandupdated_at- when the entity was created and last updated, by the clock of whoever wrote it.server_created_atandserver_updated_at- the same moments, by the server's clock.server_created_seqandserver_updated_seq- the order in which the server committed the writes.
IDs
An ID is a UUIDv7, written in base62 as 22 letters and digits, like "02x9QDX4pOzriCIlt0xKjn". Its digits run in ASCII order, 0-9, A-Z, then a-z, so IDs sort as text the same way as the UUIDs they encode. A UUIDv7 holds the time it was made, so IDs made later sort after earlier ones. Postgres stores an ID as a uuid, so SQL tools show it in the usual 36-character form. When you build an entity with its type's new function, like Task.new(title: "Write the docs"), it gets an ID right away, in the browser too. So an entity has its ID before the server has seen it, and you can point other entities at it straight away. Building Entities below covers new, and Entity.generate_id/0 makes an ID on its own.
DB.sql returns a uuid column in the 36-character form too, since Postgres can't tell an ID from any other UUID. Entity.uuid_to_id/1 turns that form into an ID. Entity.id_to_uuid/1 does the reverse, for looking up an ID in a SQL console. A DB.sql parameter for a uuid column takes either form.
An ID isn't a secret, and knowing one gives no access to the entity. The access rules decide that. It does show when the entity was created, to the millisecond, since a UUIDv7 holds that time.
Writer Time and Server Time
A write made in the browser stamps created_at and updated_at with the browser's clock, at the moment the user made the change. That's the time to show the user, and it's right even for a write made offline and sent hours later. A clock that's off moves it too, though. When an older edit arrives after a newer one, updated_at stays at the time of the newer one.
server_created_at and server_updated_at are stamped by the server when it commits the write, so all entities share one clock. In the browser, they're nil until the server has confirmed that the entity was created, and an update changes server_updated_at only once the server has confirmed it.
Server Order
Timestamps can't reliably tell you which of two writes the server committed first. server_created_seq and server_updated_seq can. They're sequence numbers that grow with every commit, in the order the server committed them, which makes them the right thing for a cursor or a read marker, like "the messages that came in after the last one this user saw":
Message |> filter(server_created_seq > ^last_seen_seq)
A sequence number is nil until it's final, which is once the server has committed the write and every write numbered before it has finished. Server queries read it as nil until then too. Sorting by one of them leaves out the entities whose number isn't final yet, except the ones written in this browser, which stay at the newest end in the order they were written. Counting doesn't leave anything out. The access rules can't use them, and the values DB.sql returns may not be final yet.
Queries covers which of the time fields to sort by, and shows how to build read markers and unread counts.
Relationships
A relationship points from an entity to other entities: relationship name, Type for one, relationship name, [Type] for many.
defmodule MyApp.Task do
use Hologram.Entity
attribute :title, :string
relationship :project, MyApp.Project
relationship :assignee, MyApp.User, optional: true
relationship :tags, [MyApp.Tag]
end
A query doesn't load a relationship unless it includes it. Until then, the field holds a %Hologram.Entity.NotIncluded{} struct rather than nil or [], so a relationship that wasn't loaded is never mistaken for an empty one. This is the same on the server and in the browser. An entity no query read holds it too, like one built with new or one a create returns. To read such a field, read the entity through a query that includes it. Queries covers include.
To check whether a relationship was loaded, call included?/1, which pages and components import. It returns false only for the struct, so nil and [] count as loaded. It works on the server and in the browser. In a template:
{%if !included?(@task.project)}
<p>Project not loaded</p>
{/if}
Matching on the struct alone works too, in a case or a function head, in server or browser code. Its fields are internal and may change:
alias Hologram.Entity.NotIncluded
case task.project do
%NotIncluded{} -> :not_loaded
nil -> :no_project
project -> project.name
end
To-One
A to-one relationship stores the related entity's ID in a field named after it with _id at the end, here project_id and assignee_id. That field is how you set it:
task = Task.new(title: "Write the docs", project_id: project.id)
A to-one is required unless it's optional: true, in which case its _id field may be nil. With unique: true, no two entities may point at the same one, which makes it one-to-one. The next section has an example.
To-Many
A to-many relationship, like tags above, is stored in a table of its own, one row per link. You change it with add_relationship and delete_relationship, which take the related entity or its ID, and then write the entity:
task = add_relationship(task, :tags, tag)
case DB.update(task) do
:ok -> ...
{:error, violations} -> ...
end
Inverses
An inverse relationship reads a relationship from the other side. MyApp.Task above points at its project with relationship :project, MyApp.Project. To list a project's tasks, declare an inverse on MyApp.Project, with inverse: naming the relationship on MyApp.Task that it reverses:
defmodule MyApp.Project do
use Hologram.Entity
attribute :name, :string
# Reverses relationship :project on MyApp.Task
relationship :tasks, [MyApp.Task], inverse: project
end
project.tasks holds the tasks whose project is that project. The name after inverse: is written bare, like a field in a query, because it's a field of MyApp.Task, not a variable. An inverse stores nothing of its own, so adding or removing one doesn't touch any data. It can't be written either. To move a task to another project, change the task's project_id.
An inverse of a to-one can be a to-one too, when the relationship it reverses is unique:
defmodule MyApp.Profile do
use Hologram.Entity
attribute :bio, :string
attribute :public, :boolean, default: false
relationship :user, MyApp.User, unique: true
end
defmodule MyApp.User do
use Hologram.Entity
relationship :profile, MyApp.Profile, inverse: user
end
A path in a filter or an access rule goes only through to-one relationships stored on the entity, so it can't go through an inverse. An inverse set can still be filtered on with any, none and all, which Queries covers. An inverse that holds one entity can't be filtered on from its side yet. Support for it is coming soon. Until then, filter from the side that stores the reference, like Profile |> filter(public == true), and include its user. An inverse takes no optional or unique, since the relationship it reverses has both.
Default Order
A to-many relationship, stored or inverse, can name the order its entities come in, with sort: and the related type's fields, written without colons:
relationship :tasks, [MyApp.Task], inverse: project, sort: [due_on: :asc, title: :asc]
An include of the relationship, or a derived field that reads it, uses this order when it doesn't give its own. It only affects reads, so changing it never moves data.
Unique Keys
A single attribute or to-one is made unique with its own unique: true option, as Options and To-One show. A unique key makes a set of fields unique together, and it's declared with unique on its own line. Here, two projects may share a slug, but not in the same workspace:
defmodule MyApp.Project do
use Hologram.Entity
attribute :slug, :string
relationship :workspace, MyApp.Workspace
unique [workspace, slug]
end
A key takes two or more attributes and to-one relationships, written as bare names, a to-one by its relationship name, and an entity type can have any number of keys. A field list that comes from code, like one a macro or a for loop builds, is pinned, and it holds the fields as atoms.
A write that would give two entities the same key fails, and every field of the key carries the reason, a to-one under its _id field:
{:error,
%{
slug: [unique: [:workspace_id, :slug]],
workspace_id: [unique: [:workspace_id, :slug]]
}}
An entity with nil in any field of the key never collides with another one. The strings in a key share one index entry, so each gets a max_bytes limit smaller than a unique string's own.
As with a unique attribute, only the server can enforce the key. Two users who create the same key while offline both see their write succeed, and the second one to reach the server has it undone. A key that's likely to be taken is better written in a command too.
Derived Fields
A derived field is a value computed from an entity's other fields, declared with derived name, type, function. The function's arguments name the fields it reads, and its body computes the value:
defmodule MyApp.Project do
use Hologram.Entity
attribute :name, :string
relationship :tasks, [MyApp.Task], inverse: project
derived :open_count, :integer, fn tasks ->
tasks
|> filter(status != :done)
|> count()
end
end
The body can use the query stages filter, sort, include, take, skip, one and count, comparisons, if, <>, and paths through to-one relationships:
derived :heading, :string, fn title, project ->
project.name <> ": " <> title
end
The type is an attribute type, an entity type for a single entity, or a list of one for several. An :enum takes its values in brackets between the type and the function, and a derived field can read another one:
derived :load, :enum, [values: [:light, :busy]], fn open_count ->
if open_count > 10, do: :busy, else: :light
end
The function doesn't run for each entity. The build runs it once and turns its body into a query expression. On the server, the field becomes part of the SQL statement that reads the entity: an if becomes a CASE WHEN, and a count becomes a subquery. In the browser, Hologram's query engine computes the same expression over the entities the browser holds. Nothing is stored, so a derived field is never out of date, and queries can filter and sort on it as on an attribute.
Since the body becomes a query, it can't call other Elixir functions, such as ones from the standard library. For other Elixir over an entity, write a plain function in the module. The body can call a function that builds a query, from another module or the entity type's own, which keeps a long query out of the declaration. It can't read the signed-in user with user_id() either, since a derived value is the same whoever reads it.
A derived field is read-only, and a query loads it only when it includes it, like a relationship:
Project |> include(open_count)
Until then, the field holds a %Hologram.Entity.NotIncluded{} struct, as a relationship does, and included?/1 returns false for it.
A derived string can't be sorted or searched, though.
Pages and components declare derived fields with the same macro, and they're the same idea: a read-only value computed from other fields and kept current. What differs is whose fields they read. A page's or component's derived field reads props, page params, state and other derived fields, so it's a value of the page or component, not of each entity. Its body is any Elixir, Hologram always computes it, and queries can't filter or sort on it. To show entities, a page or component declares a derived field whose body returns a query, and the field holds the query's result. Components covers those, and Reading Data covers showing entities with them.
Building Entities
Every entity type gets a new function that builds an entity from a keyword list or a map:
task = Task.new(title: "Write the docs", project_id: project.id)
new makes an ID unless you give one, fills in the defaults of the attributes you left out, and leaves the timestamps nil. It doesn't validate the entity or save it. DB.create does both. A to-one is set through its _id field. Giving new a relationship, an inverse or a derived field raises a Hologram.MisuseError.
When the entity type is in a variable, use Entity.new/2:
entity = Entity.new(entity_type, values)
Validation
Validation comes from the declarations, and there are no changesets. DB.create and DB.update validate the entity before they write it, in the browser and again on the server, with the same code. To check an entity before you write it, for example to show errors while the user types a value, call Entity.validate with an entity, or with an entity type and the fields to change:
iex> Entity.validate(task)
:ok
iex> Entity.validate(%{task | title: ""})
{:error, %{title: [min_length: 1]}}
iex> Entity.validate(Task, title: nil, status: :later)
{:error, %{status: [values: [:todo, :doing, :done]], title: [:required]}}
Both return :ok, or {:error, violations}, where violations maps each field that broke a rule to the list of its reasons. With an entity type and fields, only the fields given are checked. An entity holds every field, and new starts each attribute at its default, so a required attribute is :required only when its field holds nil. A default never replaces a nil you set.
The reasons:
:required- a required attribute or to-one is missing ornil.:unknown- the entity type has no field of that name.{:type, type}- the value isn't of the attribute's type.{:values, values}- the value isn't one of the enum's values.{:min, min}and{:max, max}- the value is below the minimum or above the maximum.{:in, range}- the value is outside the range.{:length, length},{:min_length, min_length}and{:max_length, max_length}- the string has the wrong length.{:format, regex}- the string doesn't match the regex.{:max_bytes, max_bytes}- the string is too long for its unique index.
A value of the wrong type is reported only with {:type, type}, and its other rules aren't checked. Writes can also fail with reasons only the server can give, like :unique and {:unique, fields}, which Writing Data covers.
Sync Mode
The browser gets every entity of a type that the user may read. For a type with too many entities for that, like a product catalog, set sync_mode to :lazy:
defmodule MyApp.Product do
use Hologram.Entity, sync_mode: :lazy
attribute :name, :string
attribute :price, :integer
allow :read
end
The browser then gets only the entities a page's fields load, plus the ones it created itself. The default is :eager. The user entity type can be lazy too, and the browser still gets the signed-in user's own entity. Reading Data covers what changes for a lazy type.
The User Entity
One entity type can stand for the app's users. Mark it with user: true:
defmodule MyApp.User do
use Hologram.Entity, user: true
attribute :email, :string, unique: true
attribute :name, :string
allow :read, when: id == user_id()
allow :update, when: id == user_id()
end
Access rules compare against the signed-in user, as user_id() does above, and roles are granted to users. Both need to know which entity type the users are.
To sign a user in, call put_user_id(server, user.id) with the user entity's ID, in a command or middleware. Hologram keeps the signed-in user for the rest of the session, which by default ends when the browser closes. Sync and Offline covers making it last longer, which matters for users who work offline. The Middleware page covers signing in and out. A user ID that no user entity can have, like an integer ID from another table, is treated as a signed-out visitor.
Pages and components get the signed-in user from the context, as an entity of the user entity type, or nil for a signed-out visitor:
prop :current_user, MyApp.User, from_context: {Hologram, :user}
The user is read with the user's own access rules, so a user entity type needs a :read rule that lets users read themselves, like the one above.
Users can't be deleted yet. DB.delete raises a Hologram.MisuseError for the user entity type, in trusted code too, and an allow :delete line on the type fails the build.