AshScenario.Multitenancy (ash_scenario v0.6.0)

View Source

Helper functions for detecting and handling multitenancy in Ash resources.

This module provides automatic detection of attribute-based multitenancy and extracts tenant values from attributes without requiring any changes to prototype or scenario definitions.

Summary

Functions

Builds create options with tenant if needed.

Extracts tenant information from attributes for a given resource.

Checks if a resource uses attribute-based multitenancy.

Checks if a resource has multitenancy configured.

Gets the multitenancy strategy for a resource.

Gets the tenant attribute name for a resource with attribute-based multitenancy.

Functions

add_tenant_to_opts(opts, tenant_value)

@spec add_tenant_to_opts(
  keyword(),
  any() | nil
) :: keyword()

Builds create options with tenant if needed.

Takes existing options and adds the tenant option if a tenant value is provided.

extract_tenant_info(resource, attributes)

@spec extract_tenant_info(module(), map()) :: {:ok, any() | nil, map()}

Extracts tenant information from attributes for a given resource.

For resources with attribute-based multitenancy, this function:

  1. Detects the tenant attribute name
  2. Extracts the tenant value from attributes
  3. Returns clean attributes without the tenant attribute

For resources without multitenancy or with context-based multitenancy, returns the original attributes unchanged.

Examples

# Resource with attribute multitenancy on :organization_id
iex> extract_tenant_info(MyApp.Post, %{title: "Test", organization_id: "org-123"})
{:ok, "org-123", %{title: "Test"}}

# Resource without multitenancy
iex> extract_tenant_info(MyApp.Blog, %{name: "Test Blog"})
{:ok, nil, %{name: "Test Blog"}}

has_attribute_multitenancy?(resource)

@spec has_attribute_multitenancy?(module()) :: boolean()

Checks if a resource uses attribute-based multitenancy.

Examples

iex> has_attribute_multitenancy?(MyApp.Post)
true

iex> has_attribute_multitenancy?(MyApp.Blog)
false

has_multitenancy?(resource)

@spec has_multitenancy?(module()) :: boolean()

Checks if a resource has multitenancy configured.

Examples

iex> has_multitenancy?(MyApp.Post)
true

iex> has_multitenancy?(MyApp.Blog)
false

multitenancy_strategy(resource)

@spec multitenancy_strategy(module()) :: :attribute | :context | nil

Gets the multitenancy strategy for a resource.

Returns :attribute, :context, or nil.

tenant_attribute(resource)

@spec tenant_attribute(module()) :: atom() | nil

Gets the tenant attribute name for a resource with attribute-based multitenancy.

Returns nil if the resource doesn't use attribute-based multitenancy.