Skip to content

oliver-kriska/claude-elixir-phoenix / targets/amp/skills/ecto-patterns

ecto-patterns

Verified

Use when a task touches Ecto, even a how-to question: schemas, changesets, validations, queries, preloads, Multi, migrations, constraints, money fields. Load it before writing Ecto code. Skip for Ash.

FileKindSize
SKILL.mdskill md3.4 KB
references/changesets.mdmarkdown4.2 KB
references/fulltext-search.mdmarkdown5.6 KB
references/migrations.mdmarkdown4.5 KB
references/queries.mdmarkdown4.8 KB
references/transactions.mdmarkdown4.4 KB

references/transactions.md

View on GitHub
# Transactions Reference

## Repo.transact (Simpler for most cases)

```elixir
Repo.transact(fn ->
  with {:ok, user} <- create_user(params),
       {:ok, profile} <- create_profile(user) do
    {:ok, user}
  end
end)
```

## Repo.transaction/1: changeset error handling

Inside the callback form `Repo.transaction(fn -> ... end)`, a bare `{:ok, _} =`
match on a write is a footgun. When the write returns `{:error, changeset}`, the
match raises `MatchError`; the transaction rolls back and **re-raises** it, so the
caller crashes (a `500` in a request) and the changeset's validation errors are
lost. It does *not* return `{:error, %MatchError{}}` — nothing catches it for you.

```elixir
# BAD — invalid changeset raises MatchError, which propagates and crashes the caller
Repo.transaction(fn ->
  {:ok, updated} = Repo.update(changeset)
  updated
end)

# GOOD — explicit case + Repo.rollback/1 preserves the changeset
Repo.transaction(fn ->
  case Repo.update(changeset) do
    {:ok, updated} -> updated
    {:error, changeset} -> Repo.rollback(changeset)
  end
end)
# => {:error, %Ecto.Changeset{}} — caller gets actionable validation errors
```

The same applies to `Repo.insert/1` and `Repo.delete/1`. For multiple steps, use
`with ... else` and roll back on the error path:

```elixir
Repo.transaction(fn ->
  with {:ok, user}    <- Repo.insert(user_changeset),
       {:ok, profile} <- Repo.insert(profile_changeset(user)) do
    profile
  else
    {:error, changeset} -> Repo.rollback(changeset)
  end
end)
```

Prefer `Repo.transact/1` (above) or `Ecto.Multi` (below) when you can — both
surface `{:error, ...}` on failure without a manual `Repo.rollback/1`, steering
you away from the bare match. This footgun is specific to the classic
`Repo.transaction/1` callback form. (Ties to the plugin Iron Laws on checking
changeset errors and matching `{:error, %Ecto.Changeset{}}` explicitly.)

## Ecto.Multi (Complex operations, testing)

```elixir
alias Ecto.Multi

# Basic Multi
Multi.new()
|> Multi.insert(:user, user_changeset)
|> Multi.insert(:profile, fn %{user: user} ->
  Profile.changeset(%Profile{user_id: user.id}, %{})
end)
|> Multi.run(:welcome_email, fn _repo, %{user: user} ->
  MyApp.Mailer.deliver_welcome(user)
end)
|> Repo.transaction()

# Composition with merge
Multi.new()
|> Multi.insert(:order, order_changeset)
|> Multi.merge(fn %{order: order} ->
  Multi.new()
  |> Multi.insert_all(:items, OrderItem, build_items(order))
end)
|> Repo.transaction()

# Reusable Multi components (default to Multi.new())
def transfer_money(multi \\ Multi.new(), from_id, to_id, amount) do
  multi
  |> Multi.run(:validate, fn _, _ -> validate_accounts(from_id, to_id) end)
  |> Multi.update(:debit, fn _ -> debit_changeset(from_id, amount) end)
  |> Multi.update(:credit, fn _ -> credit_changeset(to_id, amount) end)
end

# Error handling
case Repo.transaction(multi) do
  {:ok, %{user: user, team: team}} ->
    {:ok, user}
  {:error, :user, changeset, _changes} ->
    {:error, :user_creation_failed, changeset}
  {:error, :team, changeset, _changes} ->
    {:error, :team_creation_failed, changeset}
end

# Testing Multi without DB
multi = PasswordManager.reset(account, params)
assert [{:account, {:update, changeset, []}}] = Ecto.Multi.to_list(multi)
```

## Upsert Patterns

```elixir
# Insert or update on conflict
Repo.insert(
  changeset,
  on_conflict: {:replace, [:name, :updated_at]},
  conflict_target: :external_id
)

# Insert or do nothing
Repo.insert(changeset, on_conflict: :nothing, conflict_target: :email)

# Insert all with upsert
Repo.insert_all(
  Post,
  posts,
  on_conflict: {:replace_all_except, [:id, :inserted_at]},
  conflict_target: :external_id
)
```

## Batch Operations

```elixir
# insert_all (fast bulk insert)
Repo.insert_all(Post, posts, returning: [:id])

# update_all (fast bulk update)
from(p in Post, where: p.status == :draft)
|> Repo.update_all(set: [status: :archived, updated_at: DateTime.utc_now()])

# delete_all (fast bulk delete)
from(p in Post, where: p.inserted_at < ^cutoff)
|> Repo.delete_all()
```

## Streaming

```elixir
# For processing large result sets without loading all into memory
Repo.transaction(fn ->
  from(p in Post)
  |> Repo.stream()
  |> Stream.each(&process_post/1)
  |> Stream.run()
end)
```

## Connection Pool Tuning

```elixir
# config/runtime.exs
config :my_app, MyApp.Repo,
  pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
  queue_target: 50,
  queue_interval: 1000
```

Rule of thumb: `pool_size = (CPU cores * 2) + disk spindles`
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall