GitHub Star 1.6k

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.

The data layer is optional

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:

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:

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:

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:

Where to Go Next

Sponsored by
Curiosum
Main sponsor
Erlang Ecosystem Foundation
Milestone sponsor
Evo Store
Performance sponsor
Sruplex
Innovation partner