Data Layer
Hologram comes with a data layer. You declare your data as entity types in Elixir, and Hologram stores it in PostgreSQL, keeps a copy of the entities each user may read in their browser, and keeps the two in sync. Pages and components query that copy directly, so reading and writing data in an action happens in the browser, without waiting for the network, while the server catches up in the background.
You can use Ecto, Ash or an external API with Hologram instead. Your commands talk to it, and Hologram works as your frontend. You can also use both in one app, as Database Setup describes for Ecto. An app that declares no entity types pays nothing for the data layer. Hologram never connects to a database, and the compiler leaves the data layer's code out of the client bundles.
What the Data Layer Is
The data layer takes over the parts of an app you would usually put together yourself: the database schema, the code that maps rows to structs, the endpoints between the browser and the server, the client-side cache, and the code that keeps that cache fresh. You describe your data once, and the same Elixir code reads and writes it on the server and in the browser.
An entity type declaration covers:
- Attributes and relationships, which become tables, columns and foreign keys.
- Validation, which runs in the browser before a write is sent, and again on the server.
- Access rules, which decide who can read and write which entities, and so which entities reach each browser at all.
Relationships link entity types together, and a query follows them by name instead of joining tables, from a todo to its project and on to the project's owner. This model is sometimes called graph-relational.
The data layer is local-first. The browser holds a real database rather than a cache of responses, so a loaded page keeps answering queries when the connection drops, and writes made while offline are queued and sent once it returns.
How Data Flows
Data lives in three places:
- PostgreSQL holds the authoritative copy. Each entity type gets a table of its own.
- The oplog records every committed change in order. The server reads it to tell each connected browser what changed since it last synced.
- The browser replica holds the entities the current user may read, of the entity types the app's browser code uses. Of a lazy entity type, it holds only the ones its fields loaded. All of the app's open tabs share one replica.
A query in the browser runs against the replica and answers at once. A write in an action is applied to the replica straight away, so the page updates in the same frame, and the action's writes are sent to the server together, as one batch. The server checks the batch against validation and access rules, then commits it. If the server refuses the batch, the browser rolls the whole of it back. A committed change goes into the oplog and from there to every other browser allowed to read the entities it touched.
Server code, like init/3, commands and jobs, uses the same functions and talks to PostgreSQL directly.
Enabling It
There is no switch. The data layer starts as soon as the app declares its first entity type, a module that uses Hologram.Entity:
defmodule MyApp.Todo do
use Hologram.Entity
attribute :title, :string, min_length: 1
attribute :done, :boolean, default: false
allow :create
allow :read
allow :update
end
MyApp.Todo is an entity type. Each todo built from it, a %MyApp.Todo{} struct like the one Todo.new returns, is an entity.
Hologram finds entity types on its own, so there is no repo module to define, nothing to list them in, and nothing to add to your supervision tree.
Here is a component that lists the todos and adds the one typed into a form:
defmodule MyApp.TodoList do
use Hologram.Component
use Hologram.DB
alias MyApp.Todo
derived :todos, [Todo], fn ->
Todo |> sort(title)
end
def init(_props, component, _server) do
put_state(component, :error, nil)
end
def template do
~HOLO"""
<ul>
{%for todo <- @todos}
<li>{todo.title}</li>
{/for}
</ul>
<form $submit="add_todo">
<input name="title" />
<button type="submit">Add</button>
</form>
{%if @error}
<p>{@error}</p>
{/if}
"""
end
def action(:add_todo, %{event: %{title: title}}, component) do
todo = Todo.new(title: title)
case DB.create(todo) do
{:ok, _todo} -> put_state(component, :error, nil)
{:error, _violations} -> put_state(component, :error, "Enter a title")
end
end
end
The derived field's query runs on the server for the first render, then against the browser replica, so the list follows every change from then on, made in this tab or by another user. The action's DB.create checks the title in the browser and puts the new todo in the list before the server has seen it. An empty title breaks the min_length rule, so DB.create returns {:error, violations} instead and the component shows a message.
Before the first run, the app needs a PostgreSQL database. Database Setup covers connecting to one.
Schema Management in Dev and Production
How the database schema follows your model depends on the environment:
- In
dev, Hologram changes the database to match the model when the app starts and when live reload picks up a change. You don't need migrations while you work. - In
test,Hologram.Test.setup/0intest_helper.exsgives each test run a fresh database of its own, built from the model. The configured user must be allowed to create databases. - In every other environment, including
prod, the app applies the migrations inapp/migrationswhen it boots. When several nodes boot at once, only one of them applies them.
You don't write migrations from scratch. mix holo.gen.migration compares the migration history with the model and writes a migration for whatever the history doesn't cover yet. When it can't tell what a change means, it leaves a question in the file for you to answer. Migrations covers all of this.
use Hologram.DB
A module that queries or writes data starts with use Hologram.DB, whether it's a page, a component, a command, a seed file or a job:
defmodule MyApp.TodoQueries do
use Hologram.DB
alias MyApp.Todo
def open_todos do
Todo
|> filter(done == false)
|> sort(title)
|> DB.read()
end
end
The line brings in:
- The query stages:
filter,sort,include,take,skip,paginate,countandone. - The write stages, which record changes on an entity:
put_attribute,increment,decrement,add_relationshipanddelete_relationship. - The names
average,sum,most_commonandinverse, which are reserved for query words coming soon. A function of your own with one of these names and two arguments fails the build in a module with this line, so rename it. trust, which lets server code claim the server's own authority to go past the access rules.- The
DBalias, for running reads and writes:DB.read,DB.create,DB.update,DB.deleteandDB.transaction. Each write also has a bang version, likeDB.create!, that raises instead of returning an error, for code where a failed write would be a bug, like seeds, scripts and tests. - The
EntityandJobaliases.
Where to Go Next
- Database Setup - connecting to PostgreSQL, encrypted connections, and sharing a database with Ecto.
- Entities - attributes, relationships, validation and derived fields.
- Queries - filtering, sorting, including related entities and paginating.
- Reading Data - live reads that keep a page or component current, and one-off reads with
DB.readin actions and server code. - Writing Data - creating, updating and deleting entities, batches, transactions and conflicts.
- Access Control - who can read and write which entities.
- Roles - granting users roles, globally or on a single entity.
- Sync and Offline - what reaches the browser, how it stays current, and what happens offline.
- Migrations - taking model changes to production.
- Jobs - background work stored in the database.
- Testing - tests against a real database.
- Deploying - running the data layer in production.