defmodule MyApp.Plugs.TenantResolver do import Plug.Conn import UniEcto.Plugin, only: [set_tenant_prefix: 1] def init(default), do: default
:ok, prefix end The uni_ecto_plugin often bundles a caching mechanism. Setting a tenant prefix usually involves a database lookup to validate the tenant exists. This adds latency.
if Mix.env() == :prod do UniEcto.Plugin.set_tenant_prefix("public") end If you are searching for "uni ecto plugin," you might actually be looking for a specific adapter. Here is the landscape: uni ecto plugin
# Set the prefix for the rest of the request set_tenant_prefix(tenant)
mix uni_ecto.gen.migration create_tenants_table This creates a migration that tracks tenants in a central tenants meta-table. Add the Plug to your router: defmodule MyApp
def create_new_tenant(subdomain, company_name) do # 1. Create schema in DB prefix = "tenant_#subdomain" Ecto.Adapters.SQL.query!(MyApp.Repo, "CREATE SCHEMA IF NOT EXISTS #prefix") UniEcto.Plugin.run_migrations_for(prefix) 3. Insert tenant record into public tenants table %Tenantprefix: prefix, name: company_name |> Repo.insert!() # Runs in 'public' schema
mix uni_ecto.migrate --tenant all mix uni_ecto.migrate --tenant customer_456 In a true SaaS app, tenants are created on the fly via a signup form. if Mix
defmodule MyApp.Repo do use Ecto.Repo, otp_app: :my_app use UniEcto.Plugin, prefix_key: :tenant_prefix def all_tenants do # Could be a DB query or a static list ["public", "tenant_customer_a", "tenant_customer_b"] end end Step 3: Generate the Tenant Migrations The plugin usually provides a generator: