Queries
A query says which entities to read: which type, which of them, in what order, how many, and which related entities to bring along. The same query runs on the server, where it becomes SQL, and in the browser, where Hologram's query engine answers it from the entities the browser holds.
Most examples on this page use these entity types:
defmodule MyApp.Project do
use Hologram.Entity
attribute :name, :string
attribute :archived, :boolean, default: false
attribute :ends_on, :date, optional: true
relationship :owner, MyApp.User
relationship :tasks, [MyApp.Task], inverse: project
end
defmodule MyApp.Task do
use Hologram.Entity
attribute :title, :string
attribute :status, :enum, values: [:todo, :doing, :done], default: :todo
attribute :priority, :enum, values: [:low, :normal, :high], default: :normal
attribute :due_on, :date, optional: true
relationship :project, MyApp.Project
relationship :assignee, MyApp.User, optional: true
end
defmodule MyApp.User do
use Hologram.Entity, user: true
attribute :name, :string
attribute :email, :string
relationship :projects, [MyApp.Project], inverse: owner
end
Building a Query
A query starts from an entity type and goes through query stages, piped one after another:
Task
|> filter(status != :done)
|> sort(due_on)
|> take(20)
The query stages are filter, include, sort, take, skip, paginate, one and count, and use Hologram.DB imports them. Each one takes an entity type module or a query and returns a query. A query is plain data, a %Hologram.Query{} struct, so building one reads nothing. You can keep it in a variable, pass it to a function and add stages to it later.
The query stages are macros, like Ecto's query macros. What you write inside one isn't run as Elixir. The build turns it into data that describes the query. That's why a field is written as a bare name, and a value from your code is pinned with ^, which works like interpolation: ^today puts the value of today into the query. Pinning Values below covers the details. So a condition can't call a function on a field, like Date.diff(due_on, ^today) < 7, and a call that isn't pinned fails the build. Anything pinned is ordinary Elixir, though, so do the work on that side instead: due_on < ^Date.add(today, 7).
DB.read runs a query and returns a list of entities:
def open_tasks(project_id) do
Task
|> filter(project_id == ^project_id and status != :done)
|> sort(due_on)
|> DB.read()
end
It's the same call in an action, a command or a job. On the server it reads the database, and in the browser it reads the entities the browser holds, including the ones an action has just written. Either way, it returns only the entities the signed-in user may read, or that a visitor may read when no one is signed in. Code that runs outside a request, like seeds, Mix tasks and the console, reads everything. To show entities in a page or component and keep them current, declare a derived field whose function returns a query, either written in the function or built by a function of your own. Hologram runs the query again whenever its result could change. Reading Data covers that.
Query stages combine the way you'd read them. Two filters both apply, as if joined with and. Two includes merge. A later sort, take or skip replaces an earlier one, so take(20) |> take(50) takes 50.
Field Names
Inside a query stage, a field is written bare, like a variable: status, due_on, project. That goes for every query stage, and for the names in an entity type's sort:, inverse:, unique keys and access rule options, since they're written in the same query language. An atom fails the build:
Task |> sort(:priority)
Outside the query language, a field name is an atom, as in any other Elixir code. Compare a query stage with put_attribute, which works on the entity a query returns:
task =
Task
|> filter(status == :todo)
|> sort(due_on)
|> one()
|> DB.read()
task |> put_attribute(:status, :done)
filter and sort are query stages, so status and due_on are bare. put_attribute is an ordinary function, so it takes :status. It returns the task with the change recorded, which DB.update then writes. A field named in a validation error is an atom too.
Pinning Values
Since a bare name is a field, a value from your code is pinned with ^. Pinning works like interpolation: the query gets the value the pinned expression has when the query is built. Literals need no pin: atoms, including nil, true and false, numbers, strings and module names. Anything else is pinned, like a variable, a function call or a struct:
Task |> filter(status == :todo and priority == :high)
Task |> filter(due_on < ^Date.utc_today())
Task |> filter(assignee_id == ^user_id)
A forgotten pin reads as a field name:
Task |> filter(assignee_id == user_id)
MyApp.Task has no user_id field, so this fails, and the error says user_id probably needs a pin. Access rules read the signed-in user with user_id(), but a query can't. Pin the ID instead.
A pinned value is only ever a value. On the server, Hologram sends it to Postgres as a query parameter, apart from the SQL text, so a value typed into a form can't change what the query does. That rules out SQL injection, and you don't escape anything yourself. A pinned string never names a field either: filter(status == ^input) compares status with the text of input, whatever it holds.
Filtering
filter keeps the entities its condition holds for. The short form is a keyword list of equalities, all of which must hold:
Task |> filter(project_id: ^project_id, status: :todo)
The full form is a condition written like Elixir, with the comparison operators ==, !=, <, <=, > and >=, membership with in and not in, and and and or. and binds tighter than or, and parentheses group:
Task |> filter(priority >= :normal)
Task |> filter(status in [:todo, :doing])
Task |> filter(status not in ^closed_statuses)
Task |> filter(status == :todo and (priority == :high or due_on < ^today))
A membership list can't be empty. An integer attribute also takes a range with a step of 1, like task_count in 3..5.
Comparing Values
A value compared with an attribute has to fit the attribute's type: a Date for a :date, one of the declared values for an :enum, an ID for an :id or a relationship's _id field. A :float attribute takes integers too.
Ordering comparisons, <, <=, > and >=, work on every type except booleans and IDs, which take equality and membership only.
- An enum compares in the order its
values:lists them.MyApp.Taskdeclaresvalues: [:low, :normal, :high], sopriority >= :normalmatches:normaland:high. - A string compares in sort order, which ignores case and accents, so
name >= "M"reaches "Mango" and "mango" alike.==stays exact.
An attribute can be compared with another attribute of the same entity, like due_on < starts_on. Both must have the same type, or an integer and a float. Two enums must declare the same values in the same order.
Derived values filter like attributes, so with a task_count derived field on MyApp.Project, Project |> filter(task_count > 10) works. A derived string takes equality and membership only.
Nil
For ==, != and membership, nil is a value like any other:
Task |> filter(assignee_id == nil)
Task |> filter(due_on == nil or due_on < ^today)
So status != :done matches an entity with no status, and status not in [:done] does too, unless the list holds nil.
An ordering comparison never matches when either side is nil. due_on < ^today leaves out the tasks with no due date, so the second example above asks for them separately. A nil can't be the value of an ordering comparison either. Inside or, each side keeps its meaning, so due_on < ^today or priority == :high matches a high priority task with no due date.
Equality follows Elixir here, and ordering follows SQL. In SQL, a comparison with NULL never matches, so status != 'done' leaves out the rows with no status, and Ecto makes you write is_nil(assignee_id) instead of == nil. Here, ==, != and membership treat nil as Elixir does. An ordering comparison works like SQL instead. Elixir's term order puts nil before any date, but due_on < ^today never matches a task with no due date.
Paths Through Relationships
A condition can read a related entity's fields through a dotted path, across any number of to-one relationships:
Task |> filter(project.archived == false)
Task |> filter(project.owner.email == ^email)
Task |> filter(due_on > project.ends_on)
A path that leads nowhere reads nil, whether the relationship is empty, the related entity is gone, or the user may not read it. So assignee.email != ^email matches the tasks with no assignee. To ask for an assignee the user can read, check its ID through the path:
Task |> filter(assignee.id != nil and assignee.email != ^email)
assignee.id != nil holds only when there's an assignee the user may read. assignee_id != nil asks only whether the reference is set.
A path goes only through to-one relationships stored on the entity, not through to-many relationships, inverses or derived fields. Quantifiers, below, ask about sets. An inverse that holds one entity, like a user's profile, can't be filtered on yet. Support for it is coming soon. Until then, filter from the side that stores the reference.
In the browser, the entities along a path are downloaded with the query and kept current, whether the query includes them or not. When a task's project is archived, the first example above drops its tasks.
Text Search
starts_with and contains search a string attribute:
User
|> filter(starts_with(name, ^query))
|> sort(name)
|> take(5)
Task |> filter(contains(title, ^query))
A search ignores case and accents the way sorting does, so "jose" finds "José" and "JOSEPH", and "strasse" finds "Straße". With mode: :exact it matches the stored value byte for byte instead, for codes and other identifiers: starts_with(code, ^prefix, mode: :exact).
% and _ are plain characters. An empty term matches every entity that has a value, and an entity with no value never matches.
A pinned term doesn't narrow what the browser downloads. The browser gets every entity the rest of the filter matches and searches them itself. For a lazy entity type the server searches instead, and sends only the matches. Search from a command when the set is too big to send and the type isn't lazy, or when the attribute is server-only.
Quantifiers
any, none and all ask about a set of related entities, through a to-many relationship, an inverse or a derived field that holds a list:
Project |> filter(any(tasks))
Project |> filter(all(task <- tasks, task.status == :done))
Project |> filter(none(task <- tasks, task.assignee_id == ^user_id))
Project |> filter(any(task <- tasks, task.due_on > ends_on))
task <- tasks binds the variable task to each task in turn, as for task <- tasks does, and the condition reads the task's fields through it. Any variable name works. A bare name is still the queried entity's own field, so ends_on in the last example is the project's. Without a condition, any(tasks) asks whether there are tasks and none(tasks) whether there are none. all always takes a condition.
Over an empty set, any fails, and none and all hold. A quantifier's set can come at the end of a path, like project.tasks. Each quantifier asks about one entity at a time, so any(task <- tasks, task.status == :done and task.assignee_id == ^user_id) needs one task that's both. Related entities the user may not read don't count, and in the browser the entities a quantifier reads are kept current.
Quantifiers nest, so each one can ask about a different level:
User |> filter(all(project <- projects, any(task <- project.tasks, task.status == :doing)))
This finds the users whose every project has a task in progress. A path like projects.tasks would treat all of a user's tasks as one set. The inner condition can also read the outer name's fields, like task.due_on > project.ends_on.
Filters Built from Data
A filter chosen at runtime, like one assembled from a search form, is a pinned list of predicates:
predicates = [status: :todo, priority: {:in, [:normal, :high]}]
Task |> filter(^predicates)
Each entry pairs a field with a value or a {operator, value} tuple, using :==, :!=, :<, :<=, :>, :>=, :in, :not_in, :starts_with, :contains, :starts_with_exact or :contains_exact. A path is a list of names, and or: and any:, none: and all: take nested lists:
[
{[:project, :archived], false},
title: {:contains, query},
or: [[assignee_id: user_id], [assignee_id: nil]],
any: {[:project, :tasks], [status: :doing]}
]
Including Relationships
A query reads only the entities it asks for. Until a relationship is included, its field holds a %Hologram.Entity.NotIncluded{} placeholder. include loads it, and a dotted path includes the relationships along it:
Task |> include(project)
Task |> include(project.owner)
Project |> include([owner, tasks.assignee])
task =
Task
|> filter(id == ^id)
|> include(project)
|> one()
|> DB.read()
task.project.name
Included entities go through their own type's access rules, so a project the user may not read comes back nil, and a set leaves out the entities the user may not read. Derived fields are included by name too, the same way.
An included set comes in the order its relationship's sort: names, and in full. For part of a set, or another order, declare a derived field on the entity type and include that:
# In MyApp.Project
derived :open_tasks, [MyApp.Task], fn tasks ->
tasks |> filter(status != :done)
end
Project |> include(open_tasks.assignee)
An include chosen at runtime is pinned, like include(^relationship) or include(tasks: ^nested). A pinned include is a list of names and {name, nested} pairs.
Sorting
sort takes an attribute, a list of attributes, or a keyword list with directions:
Task |> sort(due_on)
Task |> sort([status, title])
Task |> sort(priority: :desc, due_on: :asc)
A sort reads the queried entity's own attributes, including the system attributes and derived values that aren't strings. It can't sort by a path or a relationship. A field or a direction chosen at runtime is pinned:
Task |> sort(^field)
Task |> sort(title: ^direction)
A later sort replaces an earlier one. That's unlike chaining Enum.sort_by, where the last sort wins and earlier ones break its ties. To sort by two fields, give both in one sort.
- An enum sorts in the order its
values:lists them, so with[:low, :normal, :high],sort(priority: :desc)puts:highfirst. - A string sorts the way a person would expect, ignoring case and accents, so "émile" sorts between "Emil" and "Emma".
nilgoes at the end, whether the sort is ascending or descending, sosort(score: :desc) |> take(10)returns the 10 highest scores.
Entities that tie come in ID order, which Hologram adds after every sort. So the same query returns the same order every time, on the server and in the browser, and pages never overlap. A query with no sort comes in ID order, which is roughly the order the entities were created in.
Limiting and Paging
take keeps the first entities, skip drops them, and paginate works both out from a page number and a size, counting pages from 1:
Task
|> sort(due_on)
|> take(20)
Task
|> sort(due_on)
|> skip(40)
|> take(20)
Task
|> sort(due_on)
|> paginate(page: ^page, size: 20)
The last two read the same tasks: page: 3, size: 20 skips 40 and takes 20. paginate replaces any take or skip before it. Give a paged query a sort, so its pages follow an order you chose.
Reading Data shows how to load more of a list as the user asks for it. It also covers why to cap a number that comes from the browser.
One Entity or a Count
one makes a query return its first entity, or nil when nothing matches, instead of a list. count makes it return the number of matching entities:
Task
|> filter(status == :doing)
|> sort(updated_at: :desc)
|> one()
Task
|> filter(status != :done)
|> count()
one never fails because more entities match. It takes the first in the query's order, so give it a sort when more than one can match. Both see only the entities the user may read. A query takes one of them, not both: Task |> one() |> count() raises.
To read one entity by its ID, pass its type and the ID: DB.read(Task, id). It returns nil when there's no such entity or the user may not read it.
Ordering by Time
Every entity carries three pairs of system attributes that tell when it was written, and each pair suits a different sort. Entities describes them.
created_atandupdated_atare the writer's time, when the user made the change. Sort by them for what the user sees, like a list of notes by when they were written. A write made offline keeps its time when it syncs later, but it never movesupdated_atback.server_created_atandserver_updated_atare the server's time, one clock for everyone. Sort by them to compare writes from different devices by when they arrived. In the browser, an entity the server hasn't confirmed creating yet sorts as the newest.server_created_seqandserver_updated_seqare the order the server committed writes in. Use them for a cursor that must not skip anything, like "everything that changed since I last looked":
Task |> sort(created_at: :desc)
Task
|> filter(server_updated_seq > ^last_seen_seq)
|> sort(server_updated_seq)
Two writes can share a timestamp, and a write that commits later can carry an earlier one, so a cursor over a timestamp can miss entities. A sequence number can't. The cost is that an entity's number is final only once the server has committed its write and every write numbered before it has finished. Until then it reads nil, and a query sorted by it leaves the entity out. Entities written in this browser are the exception. They show up at the newest end right away, in the order they were written, so a message the user sends appears at once. The Server Order section of Entities covers the rest, like counting, access rules and DB.sql.
Read Markers and Unread Counts
An unread count needs to know which messages came in after the last one the user saw, and server_created_seq tells you that. Store the number of the last message seen, here on a membership that joins a user to a channel, and count the messages above it:
defmodule MyApp.Membership do
use Hologram.Entity
attribute :last_seen_seq, :integer, default: 0
relationship :channel, MyApp.Channel
relationship :user, MyApp.User
derived :unread_count, :integer, fn channel, last_seen_seq ->
channel.messages
|> filter(server_created_seq > ^last_seen_seq)
|> count()
end
end
To mark the channel read, move the marker to the newest message with a final number. Filtering out nil keeps the marker from skipping past a message whose number isn't final yet, and the message counts as unread once its number arrives:
def action(:mark_read, _params, component) do
membership = component.state.membership
newest =
Message
|> filter(channel_id == ^membership.channel_id and server_created_seq != nil)
|> sort(server_created_seq: :desc)
|> take(1)
|> one()
|> DB.read()
if newest do
membership
|> put_attribute(:last_seen_seq, newest.server_created_seq)
|> DB.update()
end
component
end
The marker can move back when a user has two devices. Say they read up to message 100 on a laptop, and later open the channel on a phone that's offline and has messages only up to 50. The phone sets the marker to 50. Once it's online, its edit wins because it's the newer one, as Writing Data describes, and messages 51 to 100 count as unread again. Hologram has no write that can only raise a value yet.
Composing Queries
A query is a value, so you can build it in steps, adding a stage only when it's needed:
query = Task |> filter(status != :done)
query =
if mine? do
query |> filter(assignee_id == ^user_id)
else
query
end
query
|> sort(due_on)
|> DB.read()
A function can take a query and return one, so a condition you use in many places has a name:
def overdue(query, today) do
query |> filter(due_on < ^today)
end
Task
|> overdue(Date.utc_today())
|> sort(due_on)
The stages combine as described in Building a Query, so the order you add them in doesn't change the result, except that a later sort, take or skip replaces an earlier one.
A composed query works like any other, but the build can't follow it through variables and functions yet. It's checked when it runs, and it doesn't get its own indexes. The next two sections cover both. For a query the app runs often, write it in one piece.
Filters Built at Runtime
When the conditions themselves are data, like the fields a user filled in a filter form, build them as a list and pin the whole list:
predicates =
[status: status, assignee_id: assignee_id]
|> Enum.reject(fn {_name, value} -> is_nil(value) end)
Task
|> filter(^predicates)
|> sort(due_on)
|> DB.read()
Each entry pairs a field name with what it must match, and all of them must hold. A plain value means equality, so assignee_id: nil matches the unassigned tasks. That's why the example leaves out the fields the user didn't fill in. Other values say more:
[priority: {:>=, :normal}, due_on: {:<, today}]
[status: [:todo, :doing], estimate: 1..3]
[title: {:contains, query}]
[{[:project, :archived], false}]
An operator tuple compares, with :==, :!=, :<, :<=, :>, :>=, :in or :not_in. A list is a membership, an integer range covers its bounds, and :starts_with and :contains search. A path is the list of its names. A pinned list is the whole filter, so filter(^predicates and status == :todo) fails the build. Pass the other condition to a filter call of its own, or put an or together with it in the list: [or: [predicates, [status: :todo]]]. Write the field names in your code rather than turning user input into atoms. A name the entity type doesn't declare, or a value that doesn't fit the field, raises when the query runs.
The list can hold or and quantifiers too, so a fragment built once works as a whole filter and inside a quantifier:
open = [status: [:todo, :doing]]
busy = [any: {[:tasks], open}]
available = [or: [[assignee_id: user_id], [assignee_id: nil]]]
Task |> filter(^open)
Project |> filter(^busy)
Task |> filter(^available)
or: takes a list of predicate lists, and holds when any one of them does. any:, none: and all: pair the path to a set of related entities with a predicate list about one of them, and that list can hold quantifiers of its own. In the expression form, a pinned list can't be a quantifier's condition. Build the whole filter as data instead.
Build-Time Checks
A query written in browser code in one piece, starting from an entity type module and piped through its stages, is checked when the app builds. An unknown field, a value that doesn't fit its type or a path through a to-many relationship fails the build at the line it's on. Pinned values don't stop the check, since it only needs their place in the query, not their value.
Server code, and queries assembled from variables, helper functions or data, are checked when they run, and a mistake raises Hologram.MisuseError. A wrong form, like an atom where a field name goes, fails the build wherever the query is.
Indexes
Hologram creates database indexes for the queries it finds in your code. You don't declare them. An index can cover several fields, so this query gets one on project_id, status and due_on together:
Task
|> filter(project_id == ^project_id and status == :todo)
|> sort(due_on)
|> take(20)
The index covers the sort only when the query limits its rows, like take does here. Queries share an index when one can serve them all.
A query is found when it's written in one piece, as one call or one pipe, starting from an entity type module, an alias of one, __MODULE__ or a module attribute holding one. A query only the browser reads counts too, since the server reads the same entities to send them. Indexes are built in the background after a deploy, so they never hold up a start, and an index no query needs any more is dropped.
A query assembled from variables and functions, or filtered by a pinned predicate list, isn't found yet, so it gets only the indexes its entity type needs anyway. Write the queries an app runs often in one piece.