GitHub Star 1.6k

Reading Data

There are two ways to read entities. A page or component can hold a query, and Hologram keeps its result current as the data changes, whoever changes it. Or code can read once with DB.read, which returns the entities as they are at that moment. This page covers both, and what reaches the browser. The examples use the Project, Task and User entity types from Queries.

Live Reads

A live read is a query whose result Hologram keeps current. To read live, a page or component declares a derived field whose function returns a query. Hologram runs the query, and the field holds its result:

defmodule MyApp.ProjectPage do
  use Hologram.Page
  use Hologram.DB

  alias MyApp.Task

  route "/projects/:project_id"

  param :project_id, :id

  layout MyApp.MainLayout

  state :show_done, :boolean, default: false

  derived :tasks, [Task], fn project_id, show_done ->
    if show_done do
      Task
      |> filter(project_id == ^project_id)
      |> sort(due_on)
    else
      Task
      |> filter(project_id == ^project_id and status != :done)
      |> sort(due_on)
    end
  end

  def template do
    ~HOLO"""
    <button $click="toggle_done">Show done</button>
    <ul>
      {%for task <- @tasks}
        <li>{task.title}</li>
      {/for}
    </ul>
    """
  end

  def action(:toggle_done, _params, component) do
    put_state(component, :show_done, !component.state.show_done)
  end
end

This is the same idea as a derived field on an entity type: a read-only value computed from other fields and kept current. What differs is whose fields it reads. An entity type's derived field reads that entity's fields, so each entity has its own value, and its body is written in the query language. A page's or component's reads props, params, state and other derived fields, and its body is any Elixir, here a query. Components covers derived fields on pages and components, and Entities covers those on entity types. The function reads the project_id param and the show_done state, so clicking the button runs the query again, with the done tasks this time. The field's type matches what the query returns: [Task] for a list, Task for one and :integer for count.

A component reads live the same way, so it can show the entities it needs without a page passing them down. A live read reads as the signed-in user, or as a visitor when no one is signed in, so it returns the same entities DB.read does.

Reusing Queries

Writing a query where it's used is fine, and the build checks it and creates its indexes either way. When the same query is needed in more than one place, like a page and a command, put it in a function of a module of your own:

defmodule MyApp.Tasks do
  use Hologram.DB

  alias MyApp.Task

  def for_project(project_id, show_done) do
    if show_done do
      Task
      |> filter(project_id == ^project_id)
      |> sort(due_on)
    else
      Task
      |> filter(project_id == ^project_id and status != :done)
      |> sort(due_on)
    end
  end
end

The page's derived field then calls Tasks.for_project(project_id, show_done), a command reads the same tasks with Tasks.for_project(project_id, true) |> DB.read(), and changing the query means changing one function.

Return the whole query from the function. The build finds a query written in one piece wherever it is, so it checks this one and creates its indexes. Adding stages to the result, like Tasks.for_project(project_id, true) |> take(10), makes it a composed query. It's checked only when it runs and gets no indexes of its own, as Queries describes.

A component that holds a live read depends on the data layer. For one you want to reuse anywhere, like a task list, read in the page and pass the entities down as a prop. The component then takes a list of tasks and renders it, whatever data it gets, and it still renders again when the result changes, since the page passes it the new list.

How Live Reads Stay Current

The server renders the page first, running the query against PostgreSQL. The browser then gets the entities, starting with the types the page reads, and from then on it runs the query itself, over the entities it holds, with no request to the server. So the result changes as soon as an action writes, before the server has confirmed the write.

When another user or a job changes an entity, the server sends the change to every browser whose user may read it, and each page showing it renders again. A page needs no code for this: no subscription, no reload and no loading state. A lazy entity type is the exception. The server answers its queries, as "Lazy Entity Types" below describes.

Offline, live reads keep answering from the entities the browser holds, and their results include the writes the user makes while offline. Sync and Offline covers how the browser catches up when it reconnects.

The Signed-In User

Hologram puts the signed-in user's entity into the context under the {Hologram, :user} key, so any component can take it as a prop:

defmodule MyApp.AccountMenu do
  use Hologram.Component

  alias Hologram.UI.Link
  alias MyApp.SignInPage
  alias MyApp.User

  prop :current_user, User, from_context: {Hologram, :user}

  def template do
    ~HOLO"""
    {%if @current_user}
      <span>{@current_user.name}</span>
    {%else}
      <Link to={SignInPage}>Sign in</Link>
    {/if}
    """
  end
end

It's the entity of the user entity type, the one declared with user: true, whose ID the session holds. Hologram reads it through that type's access rules, so it's nil when the user may not read their own entity. It's nil for a visitor too, and when the app declares no user entity type. It stays current like a live read, so a change to the user's name shows up in the menu above without code.

Signing in with put_user_id or out with delete_user_id changes it. The browser then drops the entities the previous user could read and gets the ones the new user can.

A live read can use the prop like any other. To show the user's own tasks, pin the user's ID:

derived :my_tasks, [Task], fn current_user ->
  if current_user do
    Task
    |> filter(assignee_id == ^current_user.id and status != :done)
    |> sort(due_on)
  else
    []
  end
end

In access rules, user_id() names the user reading. A query can't call it yet, so pin the user's ID as above.

One-Off Reads

DB.read runs a query once and returns its result. Nothing keeps that result current, so use it in code that works with the data rather than shows it: server code, and actions.

On the Server

On the server, DB.read runs the query against PostgreSQL:

def command(:export_tasks, %{project_id: project_id}, server) do
  tasks =
    Task
    |> filter(project_id == ^project_id)
    |> sort(due_on)
    |> DB.read()

  put_action(server, :download, csv: MyApp.CSV.from_tasks(tasks))
end

A read in init/3, middleware or a command, or in any function it calls, goes through the access rules of the signed-in user, or of a visitor when no one is signed in. A read in a job, or in any function it calls, goes through those of the user or visitor who created it. A job created by server code with no session reads past the rules. It returns only the entities the user may read, an included relationship holds only the entities the user may read, one returns nil for an entity the user may not read, and count counts only what the user may read. Other server code, like seeds, Mix tasks, the console and your own plugs, reads every entity.

To read past the access rules, mark the query with trust:

Task
|> filter(project_id == ^project_id)
|> trust()
|> DB.read()

Only server code can claim the server's authority. Access Control covers when to use it.

A process you start from init/3, middleware or a command doesn't know who the user is, so DB.read in it raises a Hologram.MisuseError instead of reading as a visitor. Wrap the function you hand it with Hologram.Auth.as_current_user, called in the process that starts it:

def command(:build_report, %{project_id: project_id}, server) do
  build_report =
    Hologram.Auth.as_current_user(fn ->
      MyApp.Reports.build(project_id)
    end)

  Task.start(build_report)

  server
end

The function then reads as that user.

Hologram can't always tell that a process works for a request. A GenServer that was already running when a command calls it reads past the rules, as other server code does. So can a process started by a task that has since ended. Wrap the function in those cases too, and hand the GenServer the wrapped function to run. The same goes for writes.

In Actions

An action runs in the browser, and DB.read there reads the entities the browser holds. The browser holds only the entities the user may read, so a read in an action keeps to the access rules too. It returns at once, with no request to the server, and it sees the writes the action made on the lines before it:

def action(:select_task, %{id: id}, component) do
  put_state(component, :selected_task, DB.read(Task, id))
end

A lazy entity type can't be read this way, as "Reading Outside a Field" below describes.

The result is a copy taken when the action runs, so it doesn't change when the entity does. To show an entity that stays current, put its ID in state and read it live:

state :selected_id, :id, default: nil

derived :selected_task, Task, fn selected_id ->
  Task
  |> filter(id == ^selected_id)
  |> one()
end

def action(:select_task, %{id: id}, component) do
  put_state(component, :selected_id, id)
end

Reads in the Browser

Live reads and reads in actions run in the browser, over the entities it holds, so Hologram refuses a query the browser couldn't answer. A query that filters or sorts on a server-only attribute raises a Hologram.MisuseError, since the browser never holds the value. So does one that claims trust, since browser code reads as the signed-in user. A DB.read in a template or a derived function refuses a filter or a sort on a server-only attribute on the server too, even with trust. Run such a query in init/3 or a command.

What Reaches the Browser

The browser doesn't get the results of the queries a page runs. It gets every entity the user may read, of each entity type the browser code reads, by naming it in a query, an include or a struct pattern. A filter decides what a page shows, and the access rules decide what the browser holds, so a filter never hides an entity from a user. Once the browser holds an entity type, it can answer any query over it without asking the server. The entity types the current page reads come first.

Lazy entity types, below, work the other way: the browser gets only the entities its fields load.

An included to-one the user may not read is nil, and an included to-many leaves out the entities the user may not read. A server-only attribute holds a %Hologram.Entity.ServerOnly{} struct wherever an entity leaves the server, even in a template rendered on the server. Entities covers server-only attributes, and Sync and Offline covers how the browser stays current.

Lazy Entity Types

An entity type can have more entities than a browser should hold, like a catalog of millions of products. Declare it with sync_mode: :lazy, and the browser holds only the entities its fields have loaded, the ones it created itself, and the signed-in user's own entity when the user type is lazy:

defmodule MyApp.Product do
  use Hologram.Entity, sync_mode: :lazy

  attribute :name, :string
  attribute :price, :integer

  allow :read
end

The default is :eager, which is the sync described above. Any other value fails the build. Access rules work the same for both modes. A lazy entity the browser holds stays current like any other. A change arrives, a delete removes it, and so does losing access to it. Otherwise it stays after the page that loaded it is left, until the user signs in or out.

A live read of a lazy type is a derived field, declared like any other. The server answers it, and the page it renders carries the answers. The same goes for a query of an eager type that includes a lazy type or filters by one. When the state or a prop the field reads changes, the browser asks the server for the new answer. Until it arrives, the field keeps its last one, then changes to the new one in one step. A field with nothing to keep is empty: [] for a list, nil for one entity or a count. Reading one entity by ID with one answers at once when the browser holds the entity and the query includes no lazy type.

The user's own writes show in a list or a single entity at once where the entities the browser holds are enough to tell the result. Otherwise they show once the server answers. For example, an entity that a write moves into a limited list, like the first 20 products, shows up there once the server answers. So does one that starts to match because of a none over a lazy type. A count changes once the server answers too.

Waiting for an Answer

ready? tells whether a field shows the answer to its current query. Use it to show that a search is running, and to say "No results" only when the answer is empty:

state :term, :string, default: ""

derived :products, [Product], fn term ->
  Product
  |> filter(contains(name, ^term))
  |> sort(name)
  |> take(50)
end

def template do
  ~HOLO"""
  <input type="text" value={@term} $change="search" />

  {%for product <- @products}
    <p>{product.name}</p>
  {/for}

  {%if not ready?(:products)}
    <p>Searching...</p>
  {/if}

  {%if ready?(:products) and @products == []}
    <p>No results</p>
  {/if}
  """
end

def action(:search, params, component) do
  put_state(component, :term, params.event.value)
end

In an action, call ready?(component, :products). A field computed from a field that isn't ready isn't ready either. A prop follows the value the parent gives it, through any number of components. ready? doesn't track a value that an action or init copied into state or context. It counts as ready even when the field it came from isn't. While the server renders, every field is ready. The build warns when you ask about a field that is always ready.

Recent Queries

When a page moves on from a query, like from one search term to another, the browser keeps the query open. Going back to that term shows its answer at once. A page keeps the last 10 answered queries it no longer shows, and keeps them current. Leaving the page closes them. Going back to a page with the Back or Forward button shows the last answers, which are not ready until the server answers again.

Paging

To show a list one page at a time, pin the page number and write the size as a literal:

state :page, :integer, default: 1

derived :products, [Product], fn page ->
  Product
  |> sort(name)
  |> paginate(page: ^page, size: 20)
end

def action(:next_page, _params, component) do
  put_state(component, :page, component.state.page + 1)
end

Each page is a query of its own, so the last pages shown stay open as recent queries, and going back to one shows it at once. A user can send any page number, but never gets more than 20 products for it.

Loading More

To keep the earlier products on screen, take a number that grows:

state :num_items, :integer, default: 20

derived :products, [Product], fn num_items ->
  Product
  |> sort(name)
  |> take(^min(num_items, 500))
end

def template do
  ~HOLO"""
  {%for product <- @products}
    <p>{product.name}</p>
  {/for}
  {%if length(@products) == @num_items and @num_items < 500}
    <button $click="load_more">Load more</button>
  {/if}
  """
end

def action(:load_more, _params, component) do
  put_state(component, :num_items, component.state.num_items + 20)
end

The button shows while the list has as many products as it asked for, so it's hidden while an answer is on its way and once the products run out. The list ends at 500. The min is there for the server, since a user can send any number.

The server sends only the products the browser doesn't hold yet, and the whole list stays live. A longer list costs the server more. Each time a write touches a type the list reads, the server can run the whole query again, for every browser showing it. The shorter lists count too, since they stay open as recent queries. Keep lists short enough for that.

To show a total, declare a count. The server answers it and keeps it live, and the field shows the last number until a new one arrives:

derived :total, :integer, fn term ->
  Product
  |> filter(contains(name, ^term))
  |> count()
end

Arguments and Limits

The server rebuilds the query by running the field's own function, with the values the browser sends for its arguments. They travel to the server and come from the browser, so they are untrusted, like command params. A user can send any value a field takes, including a billion for num_items. Access rules still decide which entities the user gets. A query with a fixed size, like take(50), needs nothing more. When a value decides how much the query reads, like a number pinned in take or a page size, cap it as take(^min(num_items, 500)) does above.

Every lazy query a browser asks for may use up to 100 MB of memory and 15 seconds on the server, not counting the wait for a database connection. The same holds each time the server runs the query again. A page the server renders isn't held to these limits, so cap the numbers that come from its URL too. When a query goes over, the server refuses it and closes it, and logs an error that names the module and the field, never the arguments. The field keeps its last answer, ready? is false for it, and the tab shows a notice asking the user to reload. Going over stops only that query. The limits are per query, though, and a user can open many connections. Bound the arguments, so that each query stays cheap. A function that raises on the server is refused the same way, without a log entry.

Arguments have a size limit too. When they are too big to send, the browser says so in the console and the field stays not ready. A browser can have 256 lazy queries open at once, counting every tab. A field that doesn't fit waits, and isn't ready until another query closes.

Reading Outside a Field

You can't use DB.read on a lazy type in an action. The browser has only the lazy entities that your derived fields loaded, so the result could be incomplete. If you try, the build fails. When the build can't tell which type you're reading, the call raises a Hologram.MisuseError instead.

If a field already loaded the entities you need, read that field, like component.derived.products. To load different ones, change the state that the field's query uses. For anything else, use a command.

The argument of a lazy field can't hold a query. Pass plain values and build the query in the field.

Offline, a field whose query is open keeps its answer. The user's own writes show in it as described above. A field that needs a new answer keeps its last one and isn't ready. An app can't tell yet whether that is because the browser is offline or because the answer is on its way. Sync and Offline covers reconnecting and deploys.

Raw SQL

Queries can't group entities or compute sums, averages, minimums and maximums yet. Until they can, and for reads they aren't meant for, like window functions or a report across several entity types, DB.sql runs one SQL statement on the server:

def command(:task_stats, %{project_id: project_id}, server) do
  statement = """
  SELECT status, count(*)
  FROM "#{DB.schema_name()}"."#{DB.table_name(Task)}"
  WHERE project_id = $1
  GROUP BY status
  """

  case DB.sql(statement, [project_id]) do
    {:ok, %{rows: rows}} ->
      stats = Map.new(rows, fn [status, count] -> {status, count} end)
      put_action(server, :show_stats, stats: stats)

    {:error, _error} ->
      put_action(server, :stats_failed)
  end
end

Values go in as $1-style parameters, never into the text. It returns {:ok, %{columns: columns, rows: rows}} or {:error, %Hologram.SQLError{}}, and DB.sql! raises instead. Take the schema and table names from DB.schema_name/0 and DB.table_name/1, since they follow the model. An ID comes back as a 36-character UUID, so convert it with Entity.uuid_to_id/1 to compare it with an entity's ID.

The statement runs in UTC with ISO dates and exact float text, whatever the database server's own settings say. If due is a datetime, due::date is its UTC day. For the day in another zone, name the zone, as in (due AT TIME ZONE 'Europe/Warsaw')::date. Behind a connection pooler in transaction mode, like PgBouncer, these settings may not hold.

DB.sql skips the access rules and sees every row, so a read for a user has to keep to what that user may see in the SQL itself. Nothing removes server-only values from its rows either, so select only what the browser may see. For the same reason it raises a Hologram.MisuseError in a template or a derived function. Run it in init/3 or a command. It runs in a read-only transaction, so a write fails. Write through DB, which sends the change to the browsers. It runs only on the server, and a page whose browser code reaches it fails the build. A protocol implementation that calls it passes the build, since the server may be the only one to run it, and raises when it runs in the browser. Its one option is timeout:, 15 seconds by default.

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