cgrothaus
Patterns for making seeds idempotent?
Every freshly generated Phoenix project sports a seeds file priv/repo/seeds.exs and an accompanying mix alias ecto.setup to apply those seeds. AFAIU the seeds can only be applied once to a database.
Are there any established patterns to make the seeds idempotent? Is this a good idea at all?
Marked As Solved
cgrothaus
FTR: I came up with this solution to mark the seeds as already applied from within seeds.exs, so that running that script is idempotent.
defmodule SeedsIdempotencyHandling do
@magic_marker_value 2000_00_00_00_00_00
import Ecto.Query, only: [from: 2]
def seeds_already_applied? do
query = from m in Ecto.Migration.SchemaMigration, where: m.version == @magic_marker_value
Repo.exists?(query)
end
def mark_seeds_as_applied do
Repo.insert(%Ecto.Migration.SchemaMigration{
version: @magic_marker_value,
inserted_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
})
end
end
if SeedsIdempotencyHandling.seeds_already_applied?() do
IO.puts("Seeds already applied, skipping...")
else
# put your seeds here
SeedsIdempotencyHandling.mark_seeds_as_applied()
end
Also Liked
al2o3cr
It’s likely too much machinery for a single seed, but if you have an ongoing need for idempotent seeding there’s phil_columns:
LostKobrakai
I personally use seeds only for dummy data for development. If it changes I just drop and reapply. Everything else should imo be a (data) migration.
rcothren
That’s the best project name ever.
krasenyp
The mixture of snake and kebab case is making me uncomfortable.







