Migrations
When you change an entity type, the database has to change with it. In dev, Hologram changes the database for you. Everywhere else, the app runs migrations when it boots, and Hologram writes most of each migration.
Schema Reconciliation in Dev
In dev, Hologram compares the database with your entity types when the app starts and each time live reload picks up a change to them. Then it changes the database to match. This is called schema reconciliation. You can add, change and delete attributes, relationships and entity types freely, and write one migration when the work is ready.
Reconciliation sees only the old and the new model, so it can't tell a rename from a delete and an add. When you rename an attribute, a to-one relationship or an entity type, its dev data is deleted and the log has a warning. A migration keeps that data in production.
Some changes don't fit the data you already have, like a new required attribute without a default on a type that has entities. Hologram then refuses the change and says what to do:
cannot add required column "code" to table "task" - 2 existing rows would have no value -
declare default: <value>, make the attribute optional: true, or clear the rows - or run
mix holo.db.reset to start over, which deletes this database's Hologram data
In dev the quickest way is often to reset the database, as Resetting the Dev Database below shows.
Migrations in Production
In every environment other than dev and test, the app applies the migrations in app/migrations that the database hasn't run yet. It does this at boot, before it serves any request. When several servers boot at once, one applies the migrations while the others wait. For now, servers running the old code should be stopped first. Deploying covers how to do that on common platforms.
Each migration runs in a transaction of its own. If one fails, the database keeps the migrations before it and nothing from the failed one, and the app doesn't boot.
The app also doesn't boot when:
- The model has a change no migration covers. The error tells you to run
mix holo.gen.migration. - Someone changed Hologram's tables by hand, like adding or dropping a column.
- The database belongs to another app or another environment, or is a dev database.
A migration locks every table it changes or reads until it commits. Requests that write to those tables wait, and often the ones that read them too. Most changes take a moment, but a backfill that goes through a big table can take a while, so run it at a quiet time.
Generating a Migration
Say tasks get a priority and a new status:
defmodule MyApp.Task do
use Hologram.Entity
attribute :title, :string, min_length: 1, max_length: 200
attribute :status, :enum, values: [:todo, :doing, :blocked, :done], default: :todo
attribute :priority, :enum, values: [:low, :normal, :high], default: :normal
attribute :due_on, :date, optional: true
relationship :project, MyApp.Project
end
Run the generator:
$ mix holo.gen.migration
It compares your entity types with the migrations you already have and writes a migration for the difference:
defmodule MyApp.Migrations.V20261202164916 do
@moduledoc false
use Hologram.Migration
modify_entity MyApp.Task do
add_attribute :priority, :enum, default: :normal, values: [:low, :normal, :high]
# Tabs opened before the deploy don't know the values added to :status, so rows holding one are missing there.
# To show those rows with an older value, give add_enum_value old_clients_get: :older_value before the migration is applied.
add_enum_value :status, :blocked, after: :doing
end
end
The comment is about browser tabs that are still open on the old code. Open Tabs below covers what they get and how to change it.
The first time you run it, the migration creates all your entity types. Job types are entity types too, so their changes go into migrations the same way.
The generator then checks its work. It runs all your migrations on an empty scratch database and compares the result with your entity types. The scratch database is named after the configured one, with _shadow at the end, and is dropped afterwards. So PostgreSQL has to be running, and the configured user must be allowed to create databases.
Read the migration before you commit it, and commit it together with the change to the entity type. Access rules, derived fields and inverses aren't stored in the database, so changing them needs no migration.
Migration Files
A migration is a module in app/migrations that starts with use Hologram.Migration. The file is named after the UTC time it was generated, like 20261202164916.ex, and the module name ends with the same digits. Migrations run in that order.
The generator never changes a file it wrote. While a migration has run nowhere else, you can edit it, or delete it and generate a new one. That's also how you turn a few small migrations into one before merging a branch.
Once a database has run a migration, leave its file as it is and make further changes in a new migration. A database runs each migration only once, so an edit would never reach it. At boot, Hologram logs a warning for each migration that was edited or deleted after this database ran it. Comments and formatting don't count as edits.
A migration lists what happens to the model. The operations aren't ordinary function calls, so putting one inside an if or a comprehension has no effect on whether it runs.
Operations
These operations go at the top level of a migration:
create_entity,modify_entityanddelete_entitycreate, modify and delete an entity type. Deleting one deletes its entities.rename_entityrenames an entity type and keeps its entities. It goes first in the file, and the lines below it use the new name.add_role,modify_role,rename_roleanddelete_rolework on global role modules.designate_user_entitysays which entity type is the user one. Changing or removing an existing one also needsdelete_role_grants(), because grants belong to users of the old type.
These go inside a modify_entity block:
add_attribute,modify_attribute,rename_attributeanddelete_attribute.add_relationship,modify_relationship,rename_relationshipanddelete_relationship.add_enum_value,rename_enum_value,delete_enum_valueandreorder_enum_values.add_uniqueanddelete_unique, for unique keys.add_role,modify_role,rename_roleanddelete_role, for the roles of the entity type. Deleting a role deletes its grants.
Here's a migration that uses some of them:
rename_entity MyApp.Tag, MyApp.Label
modify_entity MyApp.Task do
rename_attribute :title, :name
modify_attribute :name, max_length: 100
rename_enum_value :status, :doing, :in_progress
add_unique [:project, :name]
delete_attribute :note
end
Operations run from top to bottom, and each one sees what the ones above it did. That's why modify_attribute uses the new name here.
Operations name fields with atoms, even in add_unique, where an entity type uses bare names. add_attribute and add_relationship take the same options as attribute and relationship in an entity type.
Changing Types
modify_attribute with type: converts the values the entities already have:
modify_attribute :estimate, type: :float
Some conversions always work: any type to :string, :integer to :float, and :date to :datetime, which becomes midnight UTC.
Others work only when every value fits: :string to :integer or :float, :float to :integer, and :datetime to :date, where each value has to be midnight UTC. If one doesn't fit, the migration fails and the error says how many don't.
Hologram doesn't convert between other types. For those, and for values that don't fit, fill a new attribute from the old one, as Functions below shows.
A to-one relationship can become a to-many one and keeps its links. The other way isn't supported, so delete the relationship and add it again.
Deleting Enum Values
delete_enum_value fails while any entity still has the value. To move those entities to another value, replace the attribute in one migration:
modify_entity MyApp.Task do
rename_attribute :status, :old_status
add_attribute :status, :enum,
values: [:todo, :done],
default: :todo,
backfill: fn old_status ->
if old_status == :doing, do: :todo, else: old_status
end
delete_attribute :old_status
end
Backfills
When you add a required field, the entities that already exist need a value for it. backfill: in the migration gives them one. It runs once and isn't part of the model, so entities created later don't get it. A default: is for both, so when the attribute has one, you don't need a backfill.
A backfill can be a fixed value, an expression or a function. It can read the entity's other fields, and it sees the data as the operations above it left it. So delete a field below the backfills that read it.
A backfill doesn't change updated_at. Its values have to follow the attribute's validation rules, and a required field can't end up with a nil. Otherwise the migration fails and the error says why.
A filled value keeps the time the field it came from last changed. If a user edited that field offline before the migration and the edit arrives after it, the newer of the two values wins, as it would have without the migration.
Constants
Write a string, a number, a boolean or an atom as it is. Pin anything that comes from the Elixir code around it with ^, like a module attribute, a function call or a sigil:
@launch_day ~D[2026-12-31]
modify_entity MyApp.Task do
add_attribute :source, :string, backfill: "web"
add_attribute :starts_on, :date, backfill: ^@launch_day
end
Every entity gets the same value, so a unique attribute needs an expression or a function.
Expressions
In an expression, a bare name is a field of the entity, and a path goes through a to-one relationship:
modify_entity MyApp.Task do
add_attribute :project_name, :string, backfill: project.name
add_attribute :label, :string, backfill: project.name <> " / " <> title
add_attribute :area, :string, backfill: title |> split(": ") |> at(0)
end
Expressions can use these:
<>joins strings. The result isnilif any part is.split(text, separator)cuts a string into parts, andat(parts, index)takes one of them, counting from 0.coalesce(value, fallback)gives the fallback when the value isnil.count(entities)counts the entities of a to-many relationship.most_common(entities, attribute)gives the value that comes up most often among them.
PostgreSQL computes an expression in one update, so it's the fastest way to fill a big table.
Functions
When an expression isn't enough, use a function. Its arguments are named after the fields it reads:
modify_entity MyApp.Task do
rename_attribute :estimate, :old_estimate
add_attribute :estimate, :integer,
optional: true,
backfill: fn old_estimate ->
case Integer.parse(old_estimate || "") do
{hours, ""} -> hours
_other -> nil
end
end
delete_attribute :old_estimate
end
This turns estimates typed as text into numbers, and drops the ones that aren't numbers. A plain type: :integer change would fail on those.
Hologram runs the function in Elixir, once for each entity. It gets nil for an empty field, so handle that. The function can have only one clause, and it reads the entity's own fields, not its relationships.
There's one exception. If the body is only a field or a path, or ends in a call to split, at, coalesce, count or most_common, it runs in PostgreSQL like an expression. For any other expression, like one with <>, wrap the body in query(...) to get the same.
Values from Related Entities
An expression reads a to-one relationship with a path and a to-many one with count or most_common:
modify_entity MyApp.Task do
add_attribute :tag_count, :integer, backfill: count(tags)
add_attribute :main_tag, :string, optional: true, backfill: tags |> most_common(name)
end
Inverses aren't part of migrations, so a project can't reach its tasks by a name. Use a function that takes the project's id and filters the tasks by it:
modify_entity MyApp.Project do
add_attribute :task_count, :integer,
backfill: fn id ->
MyApp.Task |> filter(project_id == ^id) |> count()
end
end
Required Relationships
The backfill of a to-one relationship is the entity it points to, or that entity's ID. Here the reviewer of each existing task becomes the owner of its project:
add_relationship :reviewer, MyApp.User, backfill: project.owner
project.owner_id does the same. A constant has to be an ID, and so does anything inside coalesce, like coalesce(project.owner_id, ^@admin_id).
Every ID has to belong to an entity of the right type, or the migration fails.
Making a Field Required
When an optional field becomes required, the backfill fills only the entities that have no value:
modify_attribute :due_on, optional: false, backfill: ^~D[2026-12-31]
It can be left out when every entity already has a value. If one doesn't, the migration fails.
Moving Values into New Entities
Sometimes a few attributes turn out to be an entity type of their own. Say each project has a client_name and a client_email, and you want a Client entity type instead. create makes a new client for each project from the project's values:
create_entity MyApp.Client do
add_attribute :email, :string, optional: true
add_attribute :name, :string
end
modify_entity MyApp.Project do
add_relationship :client, MyApp.Client,
backfill: create(name: client_name, email: client_email)
delete_attribute :client_email, old_clients_get: client.email
delete_attribute :client_name, old_clients_get: client.name
end
Every project gets a client of its own, even when two projects have the same client name. When the relationship is optional, a project whose values are all nil gets no client.
old_clients_get: keeps the tabs that are still open on the old code working. They go on showing the client's name and email on the project, and when a user edits one there, the server saves it in the client. A project created in such a tab gets a client too, if the access rules let the user create one. Open Tabs below has more on the option.
create can set the new entity's to-one relationships too. Give an entity under the relationship's name, or an ID under its _id field. If clients and projects both had an owner, you'd add owner: owner or owner_id: owner_id, but not both.
The new entities don't get any role grants, so if their access rules depend on roles, grant those in server code after the deploy.
Open Tabs
A browser tab that was open before a deploy still runs the old code and knows the old model. The server sends it entities in the old shape as long as it can work that shape out. When it can't, the tab shows a notice asking the user to reload. Sync and Offline covers the notice and what happens to the writes the tab makes.
Additions and renames need nothing from you. For most other changes, old_clients_get: says what those tabs get in place of what they knew:
modify_entity MyApp.Task do
add_enum_value :status, :in_review, old_clients_get: :doing
delete_attribute :summary, old_clients_get: title
delete_attribute :note, old_clients_get: nil
delete_relationship :creator, old_clients_get: project.owner
delete_relationship :tags, old_clients_get: []
end
delete_entity MyApp.Comment, old_clients_get: []
The value can be a constant, an expression or a function, as in a backfill, but not create. It's worked out from the entity as it is now and has the type the field had before. It can't read the deleted field itself or a server-only attribute. If it needs a field the same migration adds, add that field above.
The option is never required, and it doesn't change the database. You can't add it once the migration has run, so decide before you deploy.
This is what the tabs get without it and with it:
- A deleted attribute or to-one relationship. Without the option, the tabs ask the user to reload. With it, they get the value. It can be
nilif the field was optional. Usenilonly when the old code can't misread an empty field. An emptyarchived_at, for example, would make archived tasks look active. - A deleted to-many relationship or entity type. Without the option, the tabs ask the user to reload. The only value here is
[], and with it they see none. - A new enum value. Without the option, entities that have it are missing in those tabs. With it, they show up with the older value you name.
- A changed attribute type. The server converts the values back, and entities whose value doesn't fit the old type are missing, like a 1.5 where the tab expects an integer. When the new type can't be converted back, like a string that was a boolean, the tabs ask the user to reload. With the option, every entity gets its value instead.
- A required field that became optional. Without the option, entities with no value are missing. With it, they get the value.
- A to-one relationship that became a to-many one. The tabs see the link when there's only one. Entities with several are missing, unless the option says which one to show. If the relationship was required, entities with no link are missing too.
Some changes always make the tabs ask for a reload. Examples are making an attribute server-only, pointing a relationship at another entity type, deleting a role and changing the user entity type.
A value can come from a related entity, like project.owner above. If the user may not read that project, the server doesn't send the task to their old tab at all.
Old tabs also run their permission checks on the value you name, while the server checks the real one. Say a rule lets a user edit tasks that are :doing, and old tabs get :doing for tasks in review. Such a tab offers the edit, then the server refuses it and the browser undoes it. Keep the checks in mind when you pick the value.
Resolving Drafts
The generator doesn't guess when a guess could lose data. If you rename title to name, all it sees is that one attribute is gone and another is new. So it writes a draft, with a question where the operation should be:
modify_entity MyApp.Task do
# RESOLVE: :title disappeared from the attributes - :name appeared.
# Write the ops that express what happened, then delete the resolve! line. API:
# rename_attribute :old, :new - the column is renamed, its data kept
# delete_attribute :name - the column and its data are dropped
# delete_attribute :name, old_clients_get: <value or expression> - the same, but tabs opened before the deploy keep working and get this, a constant or an expression over the row's other fields
# add_attribute :name, :type, opts - a new column, empty for existing rows
# After a delete without old_clients_get, those tabs ask the user to reload.
# Looks likely: rename_attribute :title, :name
resolve! :attributes, deleted: [:title], added: [:name]
end
Replace the question with what happened:
modify_entity MyApp.Task do
rename_attribute :title, :name
end
Then run mix holo.gen.migration again. It checks the finished migration against your entity types, as it does with one it wrote in full.
You get a question when:
- Something was deleted and something of the same kind was added, which may be a rename. This covers attributes, relationships, entity types, enum values and roles.
- An attribute, a relationship or an entity type was deleted. The question is what the tabs opened before the deploy get, and the comment lists the choices. A server-only attribute has no such question, since no browser has it.
- A field is required and existing entities may have no value for it. The comment lists the ways to answer, with
backfill:among them. - The user entity type changed or was removed, which deletes all role grants.
Whatever you answer about a delete, its data is gone once the migration runs.
Changes that only leave some entities out of the open tabs, like a new enum value, aren't questions. The generator writes the operation with a comment above it that says what those tabs miss.
A draft with an open question compiles only in dev and test, so it can't get into a release.
What Migration Code May Call
A migration has to do the same thing on every database, today and in a year. So the Elixir in it can call only its own functions and the standard library functions that compute a result from their arguments, like most of Kernel, String, Enum, Map and Date.
Your app's modules, dependencies, the clock, random values and the environment aren't allowed, because their results can change. A migration that uses one doesn't compile, and the error names the line and the call.
When a backfill needs a helper from your app, copy it into the migration:
defmodule MyApp.Migrations.V20261203091500 do
@moduledoc false
use Hologram.Migration
modify_entity MyApp.Task do
add_attribute :slug, :string, backfill: fn title -> slugify(title) end
end
defp slugify(text) do
text
|> String.downcase()
|> String.replace(~r/[^a-z0-9]+/, "-")
|> String.trim("-")
end
end
To fill values that need your app's code, like a call to another service, add the field as optional and fill it after the deploy with a job.
Checking Migrations in CI
It's easy to change an entity type and forget the migration. This task catches that:
$ mix holo.check.migration
It fails when a change to the model has no migration, when a draft has an open question, or when the migrations don't run on an empty database. Otherwise it prints migrations check passed. Like the generator, it needs a running PostgreSQL and a user who can create databases.
The check runs on an empty database, so it can't tell whether a migration fits your production data. Try a migration with a conversion or a backfill on a copy of that data first.
Resetting the Dev Database
This task builds the dev database from scratch:
$ mix holo.db.reset
It creates the database if it's missing, deletes all of Hologram's data in it, builds the schema from your entity types and runs the seeds. Tables outside Hologram's two schemas stay, like those of an Ecto repo.
Stop the app and close any psql session first, because the task refuses to run while something else is connected to the database. It works only in dev and test.
Seeds
Seeds are the data a fresh dev database starts with. Put them in app/seeds.exs, and mix holo.db.reset runs that file after it builds the schema:
use Hologram.DB
alias MyApp.Project
alias MyApp.Task
alias MyApp.User
ann = DB.create!(User.new(name: "Ann"))
project = DB.create!(Project.new(name: "Website", owner_id: ann.id))
for title <- ["Write the docs", "Fix the login"] do
DB.create!(Task.new(title: title, project_id: project.id))
end
Seeds run with no user, so they write past the access rules. Use the bang functions, like DB.create!, so that a mistake stops the task with an error.