How do you structure your queries?

I use a pattern which takes an optional query function that can be injected in the list_* and get_* functions to build up the query prior to hitting the database.

def list_users(queries \\ & &1) do
  from(User)
  |> queries.()
  |> Repo.all()
end

Composable query functions are exposed on the context and can be referenced externally.

Accounts.list_users(fn query ->
  query
  |> Accounts.include_user_profile()
  |> Accounts.filter_non_executive_users()
  |> Accounts.filter_users_by_company(company)
  |> Accounts.order_users_by_first_name()
end)
4 Likes