Writing Data
DB.create, DB.update and DB.delete write entities, with the same code in actions and on the server. In an action, the write shows up in the browser at once and reaches the server after the action ends. On the server, it goes straight to PostgreSQL. Either way, every browser whose user may read the entity gets the change.
The examples use the entity types from Queries, with a counter on Project and tags on Task:
defmodule MyApp.Project do
use Hologram.Entity
# ...the fields from Queries, plus:
attribute :task_count, :integer, default: 0
end
defmodule MyApp.Task do
use Hologram.Entity
# ...the fields from Queries, plus:
relationship :tags, [MyApp.Tag]
end
defmodule MyApp.Tag do
use Hologram.Entity
attribute :name, :string, unique: true
end
Creating Entities
Build the entity with new, then write it with DB.create:
task = Task.new(title: "Write the docs", project_id: project.id)
case DB.create(task) do
{:ok, task} -> ...
{:error, violations} -> ...
end
DB.create validates the entity and writes it. It returns {:ok, entity} with the timestamps filled in, or {:error, violations} with the reasons Entities lists, and nothing is written. The entity keeps the ID new gave it, so you can point other entities at it before it's written, in the same transaction or action.
Updating Entities
DB.update writes the changes recorded on an entity. Record them with the write stages, which use Hologram.DB imports. put_attribute sets attributes, and a to-one through its _id field:
task = put_attribute(task, status: :done, assignee_id: nil)
case DB.update(task) do
:ok -> ...
{:error, violations} -> ...
end
put_attribute takes a keyword list or a map, or a name and a value: put_attribute(task, :status, :done). It sets the fields on the entity, so it shows the new values right away, and records them as changes. DB.update returns :ok or {:error, violations}, and it writes nothing when a value breaks a rule.
Only the recorded changes are written. A field you set yourself, like %{task | status: :done}, isn't recorded, and an entity with nothing recorded raises a Hologram.MisuseError. Writing only what changed is what lets two users edit different fields of one entity at the same time, as Conflicts below describes.
Counters
Some attributes count things, like the tasks in a project, the likes on a post or the items in stock. Setting one with put_attribute(project, :task_count, project.task_count + 1) loses counts. Two users who add a task at the same time both read 5 and both write 6, so the count ends at 6 instead of 7. In the browser it gets worse, since a user who was offline adds to a value that may be hours old. increment and decrement record the change instead of the result:
project = increment(project, :task_count, 1)
The write sends the amount, not the new value, so when the two users each add 1, the count ends at 7. The entity's field shows the new value right away, but the stored value is worked out at the write, from whatever the attribute holds by then. The attribute's rules, like min: and max:, are checked on that result. A counter must be an :integer attribute that isn't optional.
To-Many Relationships
add_relationship and delete_relationship add and remove links of a to-many. They take the related entity or its ID:
task =
task
|> add_relationship(:tags, urgent)
|> delete_relationship(:tags, someday)
Adding a link that's already there, or removing one that isn't, changes nothing. The relationship's field keeps what the query read, so read the entity again to see the new links. An inverse can't be written. To move a task to another project, set the task's project_id.
The write stages combine. One DB.update writes everything recorded on the entity, values, counters and links, together.
Updating by ID
When you have the ID and not the entity, give DB.update the type, the ID and the changes:
case DB.update(Task, task_id, status: :done) do
:ok -> ...
{:error, violations} -> ...
end
The changes are a keyword list or a map, as put_attribute takes them. An ID no entity has raises a Hologram.MisuseError.
Deleting Entities
DB.delete takes an entity, or a type and an ID, as in DB.delete(Task, task_id):
case DB.delete(task) do
:ok -> ...
{:error, %{referenced_by: entity_type, relationship: relationship}} -> ...
end
It deletes the entity and its to-many links. An entity another one still points at, through a to-one or a to-many link, isn't deleted. The error names the type and the relationship of the first one found, so delete those or point them elsewhere first, in the same transaction. Deleting an entity that isn't there returns :ok.
Users can't be deleted yet, so DB.delete raises a Hologram.MisuseError for the user entity type.
Transactions
DB.transaction runs a function and writes everything in it together, or nothing:
DB.transaction(fn ->
task = Task.new(title: title, project_id: project.id)
project = increment(project, :task_count, 1)
with {:ok, task} <- DB.create(task),
:ok <- DB.update(project) do
{:ok, task}
end
end)
The function returns what a write returns: :ok, {:ok, value} or {:error, reason}, and the transaction returns the same. :ok and {:ok, value} keep the writes, and {:error, reason} undoes them. Here a refused create or update leaves the with as {:error, violations}, so the task and the count are written together or not at all. Any other return value raises a Hologram.MisuseError and undoes the writes.
A refused write doesn't end the transaction, even one refused for a unique value, which would abort a plain PostgreSQL transaction. It returns its error, and the code can go on, like trying another value. Only what the function returns decides whether the writes stay. To leave from deep inside the function, call DB.rollback(reason), and the transaction returns {:error, reason}. An exception undoes the writes too, and is raised again.
A transaction inside another one undoes only its own writes when it fails, and the outer one carries on. On the server, each one costs extra statements, and past 64 in one transaction PostgreSQL slows down for every connection, so don't open one per item in a loop. The timeout: option bounds the whole transaction, 15 seconds by default. A DB.transaction doesn't cover Ecto writes, as Database Setup describes.
Writes in Actions
An action writes the same way server code does:
def action(:complete_task, %{task_id: task_id}, component) do
case DB.update(Task, task_id, status: :done) do
:ok -> put_state(component, :errors, nil)
{:error, violations} -> put_state(component, :errors, violations)
end
end
Instant Local Writes
A write in an action changes the browser's entities at once. Live reads show it when the action's component renders, and a DB.read on the next line sees it, with no request to the server. DB.create returns the entity with its server timestamps nil until the server confirms it.
The browser validates the values before it writes them, with the same code as the server, and returns the same errors. Reasons that depend on other entities, like :unique, only the server can give, so the browser lets those writes through and the server decides. The browser can only change entities it holds, and updating or deleting one it doesn't hold raises a Hologram.MisuseError. It can't set server-only attributes or claim trust either, since it acts for the signed-in user.
Browser code writes only in actions. A write anywhere else in the browser, like a derived field or a template, raises a Hologram.MisuseError.
One Action, One Batch
Every write an action makes goes into one batch, which the browser sends when the action ends and the server applies in one transaction. So an action's writes reach the server together or not at all, with no DB.transaction needed. An action that raises drops its writes before they're sent. An action chained with put_action is a separate action, with a batch of its own.
DB.transaction still works in an action, to drop some of its writes when a later one fails, by returning an error or calling DB.rollback. The writes it keeps ship in the action's batch.
Batches go to the server one at a time, in the order they were made, so a batch can change an entity that an earlier one creates. While the browser is offline, they wait, and Sync and Offline covers what happens then.
A batch can hold 8,000,000 bytes of writes, counted as the JSON the browser sends. No setting changes the limit. A write that would take the batch over it raises a Hologram.BatchTooLargeError in the action and adds nothing to the batch. Rescue it to tell the user, here with a notes attribute on Task:
def action(:save_notes, %{task_id: task_id, notes: notes}, component) do
case DB.update(Task, task_id, notes: notes) do
:ok -> put_state(component, :message, nil)
{:error, _violations} -> put_state(component, :message, "These notes aren't valid")
end
rescue
Hologram.BatchTooLargeError -> put_state(component, :message, "These notes are too long to save")
end
An action that rescues the error keeps the writes it made before, and can go on with smaller ones. To undo the earlier writes too, make them all in a DB.transaction and rescue the error outside it. To write more than one batch can hold, like a big import, split the writes between chained actions.
A proxy in front of the app has a limit of its own, which can be lower. Sync and Offline covers what to set there.
When the Server Refuses
The server checks every batch again: the values, the unique attributes and keys, the entities the to-ones point at, and the access rules. If it refuses one write, it refuses the whole batch, and the browser undoes every write in it. A created entity disappears and an updated one shows the server's values again. The batches after it still go.
An app can't see that the server refused a batch yet. Until it can, make a write the server is likely to refuse, like taking a unique name, in a command, which gets the answer back:
def command(:rename_tag, %{tag_id: tag_id, name: name}, server) do
case DB.update(Tag, tag_id, name: name) do
:ok -> put_action(server, :tag_renamed)
{:error, violations} -> put_action(server, :show_errors, violations: violations)
end
end
Writes on the Server
A write 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 write in a job goes through those of the user or visitor who created it. A job created by server code with no session writes past the rules. A write the rules refuse raises a Hologram.AccessDeniedError. Other server code, like seeds, Mix tasks, the console and your own plugs, writes past the rules. A server read follows the same rules, as Reading Data describes.
A process you start for a command's work writes only inside a function wrapped with Hologram.Auth.as_current_user, the same as it reads.
A write on the server reaches every browser whose user may read the entity, the one that sent the command included, and the pages showing it render again.
Server code has no batches. Each write in init/3, middleware or a command commits as soon as it runs, so a command that raises after a write keeps the write, even though Hologram drops its session and cookie changes and its broadcasts. To make several writes together or not at all, put them in a DB.transaction, as Transactions shows.
Writing Past the Access Rules
Some writes have no user behind them, like recording what a payment provider or another external system reported. Mark the entity with trust to write it on the server's own authority:
project =
project
|> put_attribute(:archived, true)
|> trust()
case DB.update(project) do
:ok -> ...
{:error, violations} -> ...
end
A trusted write is validated like any other, and only server code can claim it. Creating and deleting work the same way, so pipe the new entity through trust() before passing it to DB.create, or the entity to delete before passing it to DB.delete. To update or delete an entity the user may not read, read it with a trusted query first, as Reading Data shows. Access Control covers when to use it.
Conflicts
Two users can change the same entity, each from the copy their browser holds, and one of them may be offline for hours. Hologram settles it field by field, with no code from the app:
- A field only one of them changed takes that change, so two users editing different fields of one task both keep their edits.
- A field both changed takes the newer edit, by when it was made, not when it reached the server. An edit made offline at 10:00 and sent at noon loses to one made at 11:00.
- Counter moves add up, since each write sends an amount.
- A delete goes through unless someone changed the entity with an edit made later than the delete, which the deleting user never saw. Then the entity stays, every field of it.
An edit that loses isn't an error. The browser that made it shows the winning value once the server answers. A write on the server counts as made when it runs. The time of a browser's edit comes from its clock, and Sync and Offline covers how far off a clock may be.
A unique value is different. Two users taking the same name at once don't conflict field by field, so the server refuses the second write.
Errors
Besides the reasons Entities lists, a write can fail with reasons only the server can give, since they depend on other entities:
:unique- the field is unique on its own, withunique: true, and another entity already has the same value in it. For a to-one, another entity already points at the same entity.{:unique, fields}- the field is part of a unique key, which makes several fields unique together, and another entity already has the same values in all of them.fieldslists the key's fields, and each of them gets this reason, likeslug: [unique: [:workspace_id, :slug]].:not_found- a to-one points at an entity that doesn't exist.
The server checks a unique value at the moment of the write, so a value that was free when you looked can be taken by the time you write. Handle the error the write returns, rather than checking first.
Each write has a bang version, DB.create!, DB.update! and DB.delete!, that returns the result directly and raises a Hologram.WriteError instead of returning an error:
task = Task.new(title: "Write the docs", project_id: project.id)
DB.create!(task)
Use them where a failed write is a bug, like seeds, scripts and tests. In app code, use the versions that return errors and handle them with case.
Both versions raise a Hologram.AccessDeniedError when the access rules refuse a write, and a Hologram.MisuseError for a call that can't work, like an update with nothing recorded or a role grant written with DB.create. In an action, both raise a Hologram.BatchTooLargeError for a write that makes the batch too big, as One Action, One Batch shows. A job is created with Job.create, which Jobs covers.