How to read the schema name in Ecto from the runtime env var?

I am using Ecto.Adapaters.DynamoDB where the table name is suffixed with -Test and -Prod in the same AWS account. I have the table name set as environment vars which are read during runtime such as SearchFilters-Test and SearchFilters-Prod.
However when defining the schema in search_filter.ex I have the following:

schema Application.fetch_env!(:app_name, :search_filters_table_name) do
    field :accountId, :integer, primary_key: true
end

This env var here seems to be replaced by what is in config/config.exs and not config/runtime.exs. How do I supply a dynamic table name for the schema macro?

Schema is a macro, which evaluates the schema name at compile time. If that’s then you cannot customize the value at runtime / with config/runtime.exs. You can customized the table used with a schema at runtime using the {table_name, Schema} implementation for Ecto.Queryable, but you cannot change the hardcoded schema name on the module.

Do you have an example of how I would use the tuple {table_name, Schema} for the following operation?

def get_search_filters!(account_id),
    do: SearchFilter |> where(accountId: ^account_id) |> Repo.all()
def get_search_filters!(account_id),
    do: {runtime_table_name, SearchFilter} |> where(accountId: ^account_id) |> Repo.all()
2 Likes