QueryBuilder.Extension (Query Builder v1.0.1) View Source

Use this module to create an extension module to QueryBuilder for app specific query utilities. Use your query builder extension module wherever you would normally use QueryBuilder

Example:

defmodule MyApp.QueryBuilder do
  use QueryBuilder.Extension

  defmacro __using__(opts) do
    quote do
      require QueryBuilder
      QueryBuilder.__using__(unquote(opts))
    end
  end

  # Add app specific query functions
  #---------------------------------

  def where_initcap(query, field, value) do
    text_equals_condition = fn field, value, get_binding_fun ->
      {field, binding} = get_binding_fun.(field)
      Ecto.Query.dynamic([{^binding, x}], fragment("initcap(?)", ^value) == field(x, ^field))
    end

    query
    |> where(&text_equals_condition.(field, value, &1))
  end
end

defmodule MyApp.Accounts.User do
  use MyApp.QueryBuilder

  schema "users" do
    field :name, :string
    field :active, :boolean
  end
end

defmodule MyApp.Accounts do
  alias MyApp.QueryBuilder, as: QB

  def list_users(opts \\ []) do
    # Query list can include custom query functions as well:
    # [where_initcap: {:name, "john"}, where: {:active, true}]
    MyApp.Accounts.User
    |> QB.from_list(opts)
    |> Repo.all()
  end
end