Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 11 — Ecto: The Data Layer

Ecto is the persistence toolkit of the Elixir world — and for an Erlang developer it is refreshingly familiar in spirit: no hidden magic, no identity map tracking your objects behind your back. Ecto is explicit. Data goes in as plain structs, changes are validated through visible pipelines, and every query is a value you can build, inspect, and compose.

This chapter takes you from “what is a changeset?” to confidently designing a data layer the way Phoenix applications do.

11.1 Why Ecto Is Not an ORM

Classic ORMs tangle three concerns into one object: shape, validation, and persistence. Ecto splits them into three explicit pieces:

flowchart LR
    subgraph ECTO["Ecto's explicit split"]
        SC["Schema<br/>plain struct + fields<br/>knows nothing about the DB"]
        CS["Changeset<br/>cast → validate → constrain<br/>a value you can inspect"]
        RP["Repo<br/>the ONLY door to the DB<br/>every call is explicit"]
    end
    SC --> CS --> RP
PieceRoleErlang analogue
SchemaStruct + field declarationsrecord definition (-record(user, {...}))
ChangesetValidation/casting pipelinehand-written validate/1 functions
RepoBoundary module to the databaseyour mnesia/odbc wrapper module

Why this matters in practice:

  • Your schema struct is just data. You can create one without a database, serialize it, pattern-match it, send it between processes — like any term.
  • Validation never touches the DB implicitly. You decide when constraints are checked.
  • Every DB call reads Repo.something(...) at the call site. Grep your code for Repo. and you have found every place that talks to storage — the same audit property mnesia:transaction call sites give you.

From Erlang you know: if you have ever wrapped Mnesia access behind a module so callers couldn’t leak table names everywhere, you already think in contexts-and-repos. Ecto formalizes exactly that discipline.

11.2 Setting Up: The Repo Lives in Your Supervision Tree

The Repo is an OTP process (a pool of DB connections, actually). It belongs in your application’s supervision tree — which you can now read fluently after Ch 05:

defmodule Hello.Application do
  use Application

  @impl true
  def start(_type, _args) do
    children = [
      Hello.Repo,                    # ← connection pool + query runner
      {Phoenix.PubSub, name: Hello.PubSub}
      # ...
    ]

    Supervisor.start_link(children, strategy: :one_for_one, name: Hello.Supervisor)
  end
end

Configuration points at the database through config/runtime.exs:

# config/runtime.exs
import Config

if config_env() == :prod do
  config :hello, Hello.Repo,
    url: System.fetch_env!("DATABASE_URL"),   # postgres://user:pass@host/db
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
end
flowchart TD
    APP["Hello.Application"] --> SUP["Hello.Supervisor"]
    SUP --> REPO["Hello.Repo<br/>(DBConnection pool)"]
    REPO --> C1["connection proc"]
    REPO --> C2["connection proc"]
    REPO --> C3["connection proc"]
    C1 --> PG[("PostgreSQL")]

Each connection is its own supervised process — a network blip kills a connection, not your application; the pool restarts it while everything else keeps serving. This is Ch 01’s fault isolation applied to your data layer.

Adapters do the talking: PostgreSQL via postgrex, MySQL via myxql, SQLite via exqlite. Your domain code stays identical across all of them.

Inside the Pool: DBConnection Checkout Mechanics

Hello.Repo delegates to DBConnection: a query waits for a free connection from the pool, holds it for exactly one round trip, then returns it. The mechanics explain the two errors you’ll meet in production:

** (DBConnection.ConnectionError) connection not available and request was
dropped from the queue after 5000ms
  • Queue timeout: concurrent demand exceeded pool_size for longer than :queue_target/:queue_interval allow. Raising pool_size only helps if Postgres can take it; otherwise find the hot query.
  • Ownership error in tests: a process tried to use a connection checked out by another process (see §11.8).

Sizing rule of thumb: cores × 2, plus headroom for background work, capped by Postgres max_connections minus room for other clients. The pool is itself a supervised tree — inspect it with :sys.get_state(MyApp.Repo) or watch checkouts live in Observer.

11.3 Schemas: Structs With Database Mapping

A schema is Ch 02’s struct plus a mapping to table columns:

defmodule MyApp.Accounts.User do
  use Ecto.Schema            # injects schema DSL + primary key handling
  import Ecto.Changeset      # the validation functions we'll use below

  schema "users" do                       # ← table name ("users" in the DB)
    field :name, :string                  # column :name, TEXT NOT NULL? no —
    field :email, :string                 #   nullability is YOUR choice below
    field :age, :integer

    has_many :posts, MyApp.Blog.Post      # association: users.id = posts.user_id
    timestamps()                          # inserted_at / updated_at columns
  end

  # The changeset function lives HERE, next to the shape it validates.
  def changeset(user, attrs) do
    user
    |> cast(attrs, [:name, :email, :age])     # whitelist what may change
    |> validate_required([:name, :email])     # must be present after cast
    |> validate_format(:email, ~r/@/)         # local checks run immediately…
    |> validate_number(:age, greater_than: 0)
    |> unique_constraint(:email)              # …DB checks run at insert time
  end
end

Reading guide, line by line:

  • use Ecto.Schema gives you schema/2, defines __schema__ metadata, and makes %User{} a struct with a default primary key :id
  • field declares both the struct key and the column type — the type drives casting (see next section) and SQL generation
  • virtual: true fields exist on the struct but have no column — handy for form inputs like password confirmation
  • has_many does not load anything by itself. It only declares how to find related rows when you explicitly ask (§11.5 preloads)

You can also define schemas without a table (embedded_schema) — plain validated structs for forms, API payloads, config. Same changeset machinery, no database involved.

11.4 Changesets: Validation as a Visible Pipeline

The changeset is where Ecto differs most sharply from ORM habits. A changeset is itself a value — a %Changeset{} struct accumulating changes, errors, and metadata as it flows through pure functions:

flowchart TD
    IN["attrs from outside<br/>(untrusted: params, JSON, forms)"] --> CAST
    subgraph PIPE["one changeset pipeline"]
        CAST["cast/3<br/>whitelist keys + type-coerce"] --> V1["validate_required/2"]
        V1 --> V2["validate_format · validate_length · …<br/>instant, in-memory checks"]
        V2 --> UC["unique_constraint/2<br/>DECLARED here…"]
    end
    UC --> REPO["Repo.insert/1"]
    REPO --> DBCHK["…EXECUTED there:<br/>DB uniqueness check inside<br/>the same transaction"]
    DBCHK -->|"ok"| OK["{:ok, %User{}}"]
    DBCHK -->|"violation"| ERR["{:error, %Changeset{errors: [email: {#quot;has already been taken#quot;, ...}]}}"]
    V2 -->|"invalid"| INVALID["{:error, %Changeset{}}<br/>never hits the DB"]

Watch one flow end-to-end in IEx:

iex> alias MyApp.Accounts.User

iex> cs = User.changeset(%User{}, %{name: "Ada", email: "not-an-email", age: -3})
iex> cs.valid?
false

iex> Keyword.get(cs.errors, :age)
{"must be greater than %{number}",
 [validation: :number, kind: :greater_than, number: 0]}

# cast silently DROPPED unlisted keys — the whitelist is the security boundary:
iex> cs = User.changeset(%User{}, %{name: "Ada", admin: true})
iex> cs.changes
%{name: "Ada"}          # ← `admin` was discarded, not stored

The two-phase validation rule (skill worth internalizing):

Check typeRuns whenExamples
Validationimmediately, in memoryvalidate_required, validate_length, validate_format, validate_inclusion
Constraintat the DB, inside the insert/update transactionunique_constraint, foreign_key_constraint, check_constraint

Anything the database knows better than your process (uniqueness, foreign keys, race conditions) belongs in a constraint. Anything you can check without the DB belongs in a validator. Mixing these up produces either TOCTOU bugs or pointless round-trips.

Composing Changeset Functions Like Any Pipeline

Because changesets are values, validation logic composes the way your hand-written validate/1 chains do in Erlang — small named stages threaded with |>:

defmodule MyApp.Accounts.User do
  import Ecto.Changeset

  def registration_changeset(user, attrs) do
    user
    |> cast(attrs, [:email, :password])
    |> validate_required([:email, :password])
    |> validate_length(:password, min: 12)
    |> validate_confirmation(:password, required: true)
    |> put_password_hash()
  end

  defp put_password_hash(cs) do
    if cs.valid?,
      do: put_change(cs, :password_hash,
            Bcrypt.hash_pwd_salt(get_change(cs, :password))),
      else: cs
  end
end

(put_password_hash/1 only fires when every prior validator passed — and Bcrypt.hash_pwd_salt/1 comes from bcrypt_elixir.)

The verification side has a security requirement that is easy to miss, because it looks like an optimization rather than a defense:

def valid_password?(%User{password_hash: hash}, password)
    when is_binary(hash) and byte_size(password) > 0 do
  Bcrypt.verify_pass(password, hash)
end

def valid_password?(_, _) do
  # Runs the same bcrypt work against a dummy hash, so a missing user takes
  # the same time as a wrong password — otherwise response latency
  # enumerates your accounts.
  Bcrypt.no_user_verify()
  false
end

Without that second clause, “user not found” returns in microseconds and “wrong password” takes ~100ms of bcrypt work. The timing difference is a user-enumeration oracle, which is why no_user_verify/0 exists.

Custom rules are one-function validators: read the change, return the changeset or attach an error.

def validate_adult(changeset, field) do
  case get_change(changeset, field) do
    age when is_integer(age) and age < 18 ->
      add_error(changeset, field, "must be 18 or older")

    _ ->
      changeset
  end
end

# usage: |> validate_adult(:age)
#=> {:error, cs} with Keyword.get(cs.errors, :age)
#=> {"must be 18 or older", []}

For display, walk cs.errors yourself or use traverse_errors/2, which recurses into nested association changesets — the shape Phoenix forms expect.

Why Uniqueness Lives at the Database: A Race Walkthrough

Two processes registering "ada@example.com" simultaneously:

  1. Both run validate_format etc. — pass; nothing is taken yet.
  2. Both SELECT for an existing email — neither finds one.
  3. Both INSERT. Without a DB-level guarantee, both succeed.

unique_constraint(:email) makes step 3 the arbiter: the unique index admits one insert, the loser’s transaction aborts with a constraint violation, and Repo translates it into {:error, %Changeset{errors: [email: {"has already been taken", ...}]}}. Check and write share one transaction — there is no window between “looked fine” and “written”.

11.5 Queries Are Values

Queries compose as ordinary data structures before ever touching a wire:

import Ecto.Query

# keyword syntax — reads like SQL, compiles to a query struct
base =
  from u in User,
    where: u.age >= 18,
    select: {u.id, u.name}

# compose incrementally — each step returns a NEW query value
prefix = "ada"
adults_named = from u in base, where: ilike(u.name, ^"%#{prefix}%")

MyApp.Repo.all(adults_named)

Two portability notes: ilike/2 compiles on Postgres only — MySQL and SQLite need like/2 with manual case folding. And never interpolate raw user input into the pattern: "%#{prefix}%" lets a % or _ from the user widen the match. Escape them:

prefix = prefix |> String.replace(["%", "_"], fn c -> "\\#{c}" end)
from u in User, where: ilike(u.name, ^"%#{prefix}%")

The ^ pin operator binds runtime values safely — parameterized under the hood, immune to injection, exactly like prepared-statement placeholders in odbc:

min = 18
from u in User, where: u.age >= ^min
# SELECT u.id, ... FROM users AS u WHERE u.age >= $1   [$1 = 18]

Macro syntax for dynamic composition — filters stack because queries are values:

def search(opts) do
  User
  |> where([u], u.age >= ^(opts[:min_age] || 0))
  |> then(fn q -> if opts[:verified], do: where(q, [u], u.verified), else: q end)
  |> limit(^(opts[:limit] || 20))   # ← the pin matters here
  |> MyApp.Repo.all()
end

Every value crossing into the query needs ^. limit(opts[:limit] || 20) without the pin is not “unpinned dynamic value” — it is an Ecto.Query.CompileError at compile time, because the macro would otherwise treat the map access as query AST rather than as a parameter.

Dynamic, Subqueries, and Window Functions

When even conditional composition gets unwieldy, build WHERE clauses at runtime with Ecto.Dynamic:

filters =
  Enum.reduce(opts, dynamic(true), fn
    {:min_age, age}, dyn -> dynamic([u], u.age >= ^age and ^dyn)
    {:verified, true}, dyn -> dynamic([u], u.verified and ^dyn)
    _, dyn -> dyn
  end)

MyApp.Repo.all(from u in User, where: ^filters)

Subqueries nest like values because they are values — pass one anywhere a queryable fits:

top_posts =
  from p in Post,
    select: %{id: p.id},
    order_by: [desc: p.view_count],
    limit: 10

MyApp.Repo.all(from p in Post, join: t in subquery(top_posts), on: p.id == t.id)

Window functions arrive via windows: plus over/2 — e.g. ranking users by post count without leaving the DSL. And when SQL is genuinely clearer, fragment/1 escapes raw SQL inline; ^ pins stay parameterized inside it.

Preloads and the N+1 Trap

Associations never load implicitly. This is deliberate — and it prevents the classic N+1 accident:

posts = Repo.all(Post)               # 1 query
Enum.map(posts, & &1.author)         # author NOT loaded — each access returns
                                     # %Ecto.Association.NotLoaded{} (a marker
                                     # struct, not data — and not an error yet)

# Explicit preload: 2 queries total, regardless of post count:
posts = Repo.all(from p in Post, preload: :author)

# Or join-based, single query:
Repo.all(from p in Post, join: a in assoc(p, :author), preload: [author: a])
flowchart LR
    BAD["loop over 100 posts<br/>each calls fetch_author"] ===|">100 queries"| TRAP["N+1 trap<br/>(ORMs hide this;<br/>Ecto makes it impossible by default)"]
    GOOD["preload: :author<br/>once"] ---|">exactly 2 queries"| OK["constant query count"]

Six More Calls You Will Need Immediately

These are the ones every Erlang dev reaches for and then has to look up:

# nested writes — insert/update parent and children in one transaction
Repo.transaction(fn ->
  post = Repo.insert!(post_changeset)
  Repo.insert_all!(Tag, tags_for(post))
end)

# cast_assoc vs put_assoc: cast_* takes user params through the changeset
# (validated); put_* takes already-built structs (trusted).
#   cast_assoc(changeset, :comments, params)      # validate
#   put_assoc(changeset, :comments, [%Comment{}])  # insert as-is

# enum-typed field, validated against the DB's CREATE TYPE
field :status, Ecto.Enum, values: [:draft, :published, :archived]

# streaming a large table without holding it all in memory
Repo.transaction(fn ->
  Repo.stream(query, max_rows: 10_000) |> Enum.each(&process/1)
end)

# row lock inside a transaction — SELECT ... FOR UPDATE
Repo.transaction(fn ->
  {:ok, account} = Repo.one(from a in Account, where: a.id == ^id, lock: "FOR UPDATE")
  Repo.update!(account_changeset)
end)

# ask the planner what it will actually do (Postgres/MySQL)
{result, _} = Repo.with_log(fn -> Repo.all(query) end)

Repo.transaction/1 is a function with a real transaction around it, so Repo.stream and lock: only behave as documented inside one — outside, each Repo.* call is its own implicit transaction on a pooled connection. That is also why a stream outside a transaction can hand you two different connection snapshots.

Many-to-Many with join_through

Posts ↔ tags is the canonical shape — and note you own the join schema:

defmodule MyApp.Blog.PostTag do
  use Ecto.Schema

  schema "posts_tags" do
    belongs_to :post, MyApp.Blog.Post
    belongs_to :tag, MyApp.Blog.Tag
    timestamps()
  end
end

defmodule MyApp.Blog.Post do
  use Ecto.Schema

  schema "posts" do
    field :title, :string
    many_to_many :tags, MyApp.Blog.Tag, join_through: MyApp.Blog.PostTag
    timestamps()
  end
end

Reading stays declarative — one extra batched query per hop:

MyApp.Repo.all(from p in Post, preload: [:author, :tags])
# SELECT ... FROM posts;
# SELECT ... FROM authors WHERE id IN (...);
# SELECT ... FROM tags JOIN posts_tags ON tags.id = posts_tags.tag_id

Writing associates through explicit join rows via put_assoc/2:

post
|> MyApp.Repo.preload(:tags)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:tags, [existing_tag, %Tag{name: "beam"}])
|> MyApp.Repo.update()

Mnesia veterans will recognize the discipline: no implicit link traversal — every hop across tables appears in the code.

Write-side helpers mirror read-side explicitness: Repo.insert(cs), Repo.update(cs), Repo.delete(user), and Ecto.Multi for multi-step transactions you compose and inspect like any pipeline (see Explore More).

11.6 Migrations Ship With Mix

Schema evolution is versioned, reviewable Elixir:

mix ecto.gen.migration add_users
# → priv/repo/migrations/20260825120000_add_users.exs
defmodule Hello.Repo.Migrations.AddUsers do
  use Ecto.Migration

  def change do
    create table(:users) do
      add :name, :string, null: false
      add :email, :string, null: false
      add :age, :integer

      timestamps()
    end

    create unique_index(:users, [:email])   # backs unique_constraint above!
  end
end
mix ecto.create       # create the database itself
mix ecto.migrate      # apply pending migrations, tracked in schema_migrations
mix ecto.rollback     # revert last migration (change/1 runs in reverse)
mix ecto.migrations   # show applied/pending status

Note the pairing: unique_constraint(:email) in the changeset works only because unique_index(:users, [:email]) exists in a migration. Declare the constraint without the index and nothing fails loudly — duplicates simply insert and your “uniqueness” silently protects nothing. The changeset declaration is a translator for a database error; no index means no error to translate.

Upserts: on_conflict

Insert-or-update races dissolve into one statement — SQL ON CONFLICT, expressed as options:

# create-or-increment a counter row, atomically:
MyApp.Repo.insert!(
  %Counter{slug: "hits", count: 1},
  on_conflict: [inc: [count: 1]],
  conflict_target: :slug
)

# simplest valid form — SET a column to a literal value:
MyApp.Repo.insert(changeset, on_conflict: [set: [name: "unknown"]],
                          conflict_target: :email)

# read-back variant — return the surviving row:
{:ok, user} =
  MyApp.Repo.insert(changeset,
    on_conflict: {:replace, [:name, :updated_at]},
    conflict_target: :email,
    returning: true
  )

:on_conflict accepts :raise, :nothing, {:replace, fields}, a keyword list of update instructions such as [set: …] or [inc: …], or an Ecto.Query built with update:. The keyword form covers simple updates; reach for the query form when the update needs more than a single instruction. All of it executes in the same statement — the compare-and-swap your Mnesia transactions did by hand, delegated to the database where it belongs.

conflict_target must match a unique index (see unique_index/3 above). Without one the database raises a constraint error rather than taking the branch you intended.

Data Migrations Are Separate Beasts

Once tables settle, backfills get their own versioned modules — and their own reversibility decisions:

defmodule Hello.Repo.Migrations.BackfillUserSlugs do
  use Ecto.Migration

  def up do
    execute """
    UPDATE users
    SET slug = lower(regexp_replace(name, '\\s', '-', 'g'))
    WHERE slug IS NULL
    """
  end

  def down, do: :ok          # backfills are usually irreversible by design
end

Rule of thumb: DDL goes in change/1 (auto-reversible), bulk data in up/0/down/0. Large backfills belong in batches or Oban jobs (Ch 13) — not one giant UPDATE holding locks for minutes.

Runnable note: want to try the full round-trip right now? In Livebook:

Mix.install([{:ecto_sql, "~> 3.12"}, {:exqlite, "~> 0.16"}])

Define a Repo and run a migration. The exqlite adapter takes a filename, not a URL — ":memory:" is the whole value:

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.SQLite3
end

# config/config.exs (Livebook: Config.put/3 or a config.exs)
config :my_app, MyApp.Repo, database: ":memory:"

{:ok, pid} = MyApp.Repo.start_link()
Ecto.Migrator.run(MyApp.Repo, [{1, "create users", fn repo ->
    Ecto.Adapters.SQL.query!(repo, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
end}], :up, all: true, log: false)

That is the complete throwaway database: an adapter module, a config key, a started Repo, and a migration.

11.7 Contexts: The Public API of Your Domain

Phoenix’s architectural convention (and a good one even without Phoenix): never call Repo or build queries outside context modules. Controllers, LiveViews, workers — everyone talks to a context’s public functions:

defmodule MyApp.Accounts do
  @moduledoc "Public API for user accounts."

  alias MyApp.Accounts.User
  alias MyApp.Repo

  @doc "Registers a user; returns {:ok, user} or {:error, changeset}."
  def register_user(attrs) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end

  @doc "Fetches a verified user by email."
  @spec get_verified_user_by_email(String.t()) :: {:ok, User.t()} | {:error, :not_found}
  def get_verified_user_by_email(email) do
    case Repo.one(from u in User, where: u.email == ^email and u.verified) do
      nil -> {:error, :not_found}
      user -> {:ok, user}
    end
  end
end

Benefits you’ll recognize from good Erlang module design:

  • Callers depend on intent (Accounts.register_user/1), not table shapes
  • Swapping storage details never ripples beyond the context
  • The context is the natural seam for authorization, telemetry, caching

Ecto.Multi: Transactions You Can Inspect Before Running

Ecto.Multi is to transactions what pipelines are to data: a named, ordered, inspectable value. Nothing executes until Repo.transaction:

alias Ecto.Multi

Multi.new()
|> Multi.insert(:user, User.changeset(%User{}, attrs))
|> Multi.run(:prefs, fn repo, %{user: user} ->
  repo.insert(Preference.changeset(%Preference{}, %{user_id: user.id}))
end)
|> Multi.run(:audit, fn _repo, %{user: user} ->
  # non-bang: a bang version raises, which aborts the caller's process and
  # loses the {:error, step, value} naming that Multi exists to give you
  AuditLog.record("signup", user.id)
end)
|> MyApp.Repo.transaction()
#=> {:ok, %{user: %User{}, prefs: %Preference{}, audit: %AuditLog{}}}

# any step failing rolls back everything and names the culprit:
#=> {:error, :prefs, %Ecto.Changeset{}, %{user: %User{}}}

Because a Multi is data, you can unit-test the steps dry, append steps conditionally before execution, and log the exact plan — compositional control your mnesia:transaction(fun) closures never had.

11.8 Testing: Sandbox Mode Explained

ExUnit + Ecto give transactional test isolation using the database’s own mechanism:

defmodule MyApp.AccountsTest do
  use ExUnit.Case, async: true          # tests run CONCURRENTLY

  alias MyApp.{Accounts, Repo}

  setup do
    # Checks out a connection and opens a transaction for this test:
    pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Repo, shared: not is_nil(System.get_env("CI")))
    on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
    :ok
  end

  test "registers with valid attrs" do
    assert {:ok, %User{id: id}} = Accounts.register_user(%{
             "name" => "Ada", "email" => "ada@example.com"
           })

    # No account is verified by registration, so this returns :not_found —
    # which is the assertion you want. Flip it to {:ok, _} only after adding
    # a verification step to the context.
    assert {:error, :not_found} = Accounts.get_verified_user_by_email("ada@example.com")

    assert {:ok, %User{id: ^id}} = Accounts.get_user_by_email("ada@example.com")
  end

  test "rejects duplicate email" do
    attrs = %{"name" => "A", "email" => "dup@example.com"}
    assert {:ok, _} = Accounts.register_user(attrs)
    assert {:error, %Ecto.Changeset{}} = Accounts.register_user(attrs)
  end
end

What actually happens:

sequenceDiagram
    participant T as Test process
    participant POOL as Repo pool
    participant DB as PostgreSQL
    T->>POOL: start_owner! (checkout connection)
    POOL->>DB: BEGIN
    Note over T,DB: test body — all inserts happen<br/>inside this transaction
    T->>POOL: stop_owner (on_exit)
    POOL->>DB: ROLLBACK
    Note over DB: zero residue — other tests<br/>never saw this data

Because isolation comes from transactions (not truncation), tests are fast and async: true scales across cores — BEAM concurrency applied to your test suite. One caveat to respect: code that spawns unsupervised processes inside tests must share ownership explicitly, which is why generated apps enable pool: Ecto.Adapters.SQL.Sandbox in config/test.exs.

Ownership Deep Dive: Who May Touch Which Connection

The sandbox enforces one rule: only the owning process may use checked-out connections. start_owner! checks out a connection, opens a transaction, and returns an owner pid; processes in that test’s ancestry share it. The classic failure modes map directly:

SymptomCauseFix
cannot find ownership processspawned Task hits the Repogrant access with Sandbox.allow/3
Passes alone, fails in suitedata leaked across async testsunique emails per test
Nested Task hangschild waits on parent’s connectionallow before spawning

The signature is Sandbox.allow(repo, parent, allow, opts \\ []) — the repo comes first, and allow is the pid being granted access:

# in the parent test process, BEFORE spawning:
Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, self(), worker_pid)

allow/3 is allow/4 with an empty opts list; parent must already have checked out a connection or you get :not_found. That ordering rule is the whole reason for the “allow before spawning” row in the table — explicit capability passing, familiar discipline from Erlang process bookkeeping.

Non-async suites skip all of this and call Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, {:shared, self()}) in test_helper.exs, sharing the owner with every process of that test.

11.9 From Erlang You Know: Ecto ↔ Mnesia

ConcernMnesia habitEcto equivalent
Schema definitionrecord + mnesia:create_tableschema + migration
Transactionmnesia:transaction/1implicit per Repo.* call; Ecto.Multi for composed ones
Consistency checkshand-written guardschangeset validators + DB constraints
Cross-nodedistributed tablesrely on Postgres replication
Dirty readsdirty_read/1 (fast, unsafe)no direct equivalent — issue raw SQL, and understand you have left Ecto’s guarantees
Isolation levelsmnesia:activity/3 kind (transaction vs dirty)Repo.transaction/2, isolation: :serializable etc. — set explicitly, same idea

Mnesia stays available from Elixir (:mnesia...) — some systems pair both: Mnesia for hot ephemeral state, Ecto/Postgres for durable relational data.

Explore More

  • Ecto guides — the four-book series: Getting Started, Changesets, Querying, Multi
  • Ecto.Multi — compose transactions as inspectable pipelines; the answer to “how do I do several writes atomically”
  • Ecto.Query API — window functions, CTEs, fragments for the escape hatches
  • SQL Sandbox docs — ownership modes explained (shared, manual, auto)
  • Exercise idea: port one of your Mnesia tables to Ecto + SQLite in a Livebook, keeping the accessor signatures identical — feel where the changeset boundary adds value

Checkpoint

  1. Which Ecto piece validates input before it reaches your schema struct?
  2. Why does cast/3 dropping unknown keys matter for security?
  3. What is the difference between validate_required/2 and unique_constraint/2 in terms of when they run?
  4. How many queries does preload: :author issue for 100 posts?
  5. What makes sandbox-mode tests safe to run with async: true?
Answers
  1. The changeset (cast/3 + validators); the schema stays a plain struct.
  2. Whitelisting means untrusted input cannot set privileged fields (like an admin flag) no matter what keys attackers submit — mass-assignment is structurally impossible.
  3. Validators run immediately in memory during the pipeline; constraints are declared in the changeset but executed by the database inside the insert/update transaction — catching races the validators can’t.
  4. Two: one for posts, one batched fetch of all referenced authors.
  5. Each test owns a connection running inside a transaction that is rolled back on exit, so concurrent tests see isolated snapshots of the DB.

Next: Chapter 12 — Ash: Declarative Domain Modeling