Uni Ecto Plugin
In the modern landscape of Software as a Service (SaaS), multi-tenancy is no longer a luxury—it’s a necessity. Whether you are building a white-label CRM, an enterprise ERP, or a simple API for startups, you need a way to isolate customer data securely.
If you are an Elixir developer using Phoenix Framework and Ecto, you have likely heard the siren call of the uni_ecto_plugin.
While Ecto provides the foundation for database communication, the uni_ecto_plugin extends its capabilities to handle the complex routing, migrations, and query scoping required for robust multi-tenant architectures. In this article, we will dive deep into what this plugin is, why you need it, and how to master its implementation. uni ecto plugin
alias Uni.Ecto
step = Ecto.insert(changeset)
lib/uni_ecto_plugin/tenancy.ex
defmodule UniEctoPlugin.Tenancy do defmacro __using__(opts) do tenant_field = Keyword.get(opts, :tenant_field, :tenant_id)quote do import Ecto.Query @tenant_field unquote(tenant_field) field @tenant_field, :integer def scope_tenant(query, tenant_id) do from q in query, where: field(q, ^@tenant_field) == ^tenant_id end def set_tenant(changeset, tenant_id) do Ecto.Changeset.put_change(changeset, @tenant_field, tenant_id) end def before_insert(changeset, tenant_id) do set_tenant(changeset, tenant_id) end end
end end
Usage:
defmodule MyApp.Blog.Comment do use Ecto.Schema use UniEctoPlugin.Tenancy, tenant_field: :account_id
schema "comments" do field :content, :string timestamps() end end