AshSqlite.MultiTenancy (ash_sqlite v0.3.0)

Copy Markdown View Source

A AshSqlite.Repo.tenant_repo/2 implementation that gives each tenant its own database file.

A tenant's file is opened and migrated on first use, and the repo's init/2 sees the tenant as config[:tenant]. Only dir is required. max_children defaults to :infinity and open_timeout, in milliseconds, to 15000.

config :my_app, MyApp.Repo,
  tenants: [
    dir: "priv/tenants",
    migrations_path: "priv/repo/tenant_migrations",
    max_children: 1_000,
    open_timeout: 15_000
  ]

defmodule MyApp.Repo do
  use AshSqlite.Repo, otp_app: :my_app

  def tenant_repo(tenant, context),
    do: AshSqlite.MultiTenancy.tenant_repo(__MODULE__, tenant, context)
end

Summary

Functions

The name, without its .db extension, of the file tenant's database is stored in.

The repo instance serving tenant, opening its database if it is not open.

Functions

encode(tenant)

@spec encode(String.t()) :: String.t()

The name, without its .db extension, of the file tenant's database is stored in.

Escapes rather than sanitises, so no two tenants share a file, even on a case-insensitive filesystem, and no tenant names a path outside dir. Lowercase letters, digits, -, _ and . are kept, and every other byte becomes ~ and two lowercase hex digits:

iex> AshSqlite.MultiTenancy.encode("Acme:2026")
"~41cme~3a2026"

Raises ArgumentError for a tenant that is not a non-empty binary, or that encodes to more than 244 bytes.

tenant_repo(repo, tenant, context)

@spec tenant_repo(module(), term(), map()) :: pid()

The repo instance serving tenant, opening its database if it is not open.