Queryable (queryable v0.1.0) View Source

Queryable injects query utility functions inside an Ecto Schema.

Example

defmodule Person do
  use Queryable #instead of Ecto.Schema
  schema "persons" do
    field :name, :string
    field :surname, :string
    field :age, :integer
  end

  criteria(under: age, where: el.age < ^age)
  criteria(ordered_by: field, order_by: ^field)
end

Using Queryable within an Ecto Schema creates a function &query/1 that accepts a list of optional keywords, each one corresponding to a schema field or to a virtual field declared on a criteria, and returns an Ecto Query. A typical usage is the following:

iex> Person.query(name: "John", under: 18)
iex> #Ecto.Query<from s0 in Person, where: s0.name == ^"John", where: s0.age < ^18>

Furthermore, for each field or virtual field, a builder function with the same name is created. For example, the previous query can be rewritten using builder:

iex> Person.name("John") |> Person.under(18)
iex> #Ecto.Query<from s0 in Person, where: s0.name == ^"John", where: s0.age < ^18>

The latter option enables compile time checks (eg: dialyxir) if you want to be sure you are building the query properly.

Link to this section Summary

Functions

Create a virtual field that can be queried.

Link to this section Functions

Link to this macro

criteria(list)

View Source (macro)

Create a virtual field that can be queried.

Example

criteria(under: age, where: el.age < ^age)
criteria(ordered_by: field, order_by: ^field)

You can also use pattern matching.

Example

criteria(age: [from, to], where: el.age >= ^from and el.age <= ^to)
criteria(age: age, where: el.age == ^age)

If you define a custom criteria for schema field, default query for that field will be replaced.

N.B. Object must be referred using el keyword.