DEV Community

Cover image for Techniques for Idempotency in seeds.exs

Techniques for Idempotency in seeds.exs

Byron Salty on January 09, 2024

Idempotency is an annoying word that makes people think you are an asshole when you use it, at least if they aren't exactly sure what it means. B...
Collapse
 
andreasknoepfle profile image
Andreas Knöpfle

We usually do upserts and hardcode the primary key, since there is always a unique constraint on it:

book_category =   Repo.insert!(
    %Category{name: "Books", id: "f671a68d-3042-4269-8067-89a78a11be48"},
    on_conflict: :nothing
  )
Enter fullscreen mode Exit fullscreen mode

This has some advantages:

  • You can write development tools that make some assumptions on ids (mock servers, etc)
  • You can bookmark development resources that were seeded, since they will have the same paths even if their primary key is in the routes

The only downside is that one has to manage the primary keys a bit.

Collapse
 
byronsalty profile image
Byron Salty

This is awesome. Exactly the type of feedback that I was hoping to get.

The other piece that it seems you are doing differently than me is non-sequential ids. Probably a good idea in any case.