Use UUID as Primary Key for entire app

Hey all!

I’m writing an offline-first app in React Native for which Phoenix is an API only. Due to the syncing needs of my front-end DB, I need unique IDs app-wide, not just per table. So, I plan to use UUIDs as my primary key for everything.

Does anyone have pointers for setting this as a default behavior for the entire app? I know how to set up UUIDs per table, but it would be nice if I could abstract it and not need to implement it custom for each table.

defmodule Project.MySchema do
  defmacro __using__(opts) do
    use Ecto.Schema, unquote(opts)
    @primary_key {:id, :binary_id, autogenerate: true}
    @foreign_key_type :binary_id

And then in modules with schema just use Project.MySchema


Thanks! That’s helpful.

That would not alter the steps needed during the migration, though.

I hoped to find a way to override Ecto’s default implementation. For example, when migrating, if one does nothing regarding the primary key, you’ll get an auto-incrementing primary key. I wondered if there was a way to override that Ecto behavior.

If you are talking about the generators you can change it in your config.exs file:

config :your_app, yourapp.repo, migration_primary_key: [type: :uuid]