oliver-kriska/claude-elixir-phoenix / targets/codex/skills/ecto-patterns
ecto-patterns
VerifiedUse when a task touches Ecto, even a how-to question: schemas, changesets, validations, queries, preloads, Multi…
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.3 KB |
| references/changesets.md | markdown | 4.2 KB |
| references/fulltext-search.md | markdown | 5.6 KB |
| references/migrations.md | markdown | 4.5 KB |
| references/queries.md | markdown | 4.8 KB |
| references/transactions.md | markdown | 4.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`
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |