# `PgRest.Ecto.Filter`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/ecto/filter.ex#L1)

Compiles PostgREST filter AST nodes (`PgRest.AST.Condition`, `PgRest.AST.Logic`) into
`Ecto.Query.dynamic/2` expressions, for applications that parse PostgREST filters with
`PgRest.Grammar.Filter` and run the query through their own Ecto code instead of
`PgRest.Plug`.

    {:ok, status} = PgRest.Grammar.Filter.parse_condition("status", "in.(active,draft)")
    {:ok, cheap} = PgRest.Grammar.Filter.parse_logic("or", "(price.lt.10,qty.gte.100)")

    {:ok, query} = PgRest.Ecto.Filter.where(Product, [status, cheap])
    Repo.all(query)

Every value is a bind parameter; no request text is spliced into SQL. Conditions bind
to the query's first binding.

## Field names and casting

Field names resolve against an allowlist, never by creating atoms:

  * `:schema` - an Ecto schema module. Its fields are filterable and each value is cast
    with `Ecto.Type.cast/2` against the field's type, so `qty=eq.abc` is a `22P02`
    before the query runs. `where/3` defaults it to the query's schema; pass
    `schema: nil` to skip casting.
  * `:fields` - a list of field atoms that may be filtered. With `:schema` it narrows
    the schema's fields; without one it is required and values bind uncast, as the
    strings the grammar produced. Postgrex encodes parameters in binary, so an uncast
    string only matches a text-like column (`text`, `varchar`, `citext`, enums); filter
    other columns through a `:schema`.

A name outside the allowlist is a `42703`. Passing neither option raises
`ArgumentError`.

Supported operators: `eq neq gt gte lt lte isdistinct in like ilike match imatch is cs
cd ov fts plfts phfts wfts`, with `not.` and `and`/`or` trees. JSON paths, `any`/`all`
modifiers and range operators are refused with a `PGRST100`. The
[Filtering Ecto queries](ecto-filter.md) guide has the operator table.

# `ast`

```elixir
@type ast() :: PgRest.AST.Condition.t() | PgRest.AST.Logic.t()
```

# `option`

```elixir
@type option() :: {:schema, module() | nil} | {:fields, [atom()]}
```

# `to_dynamic`

```elixir
@spec to_dynamic(ast(), [option()]) ::
  {:ok, Ecto.Query.dynamic_expr()} | {:error, PgRest.Error.t()}
```

Compiles one filter node to a dynamic expression over the query's first binding.

Returns `{:error, %PgRest.Error{}}` for an unknown field (`42703`), a value the field
type rejects (`22P02`), or an unsupported filter or a value of the wrong shape for its
operator, such as an `is` value other than `null`, `not_null`, `true`, `false` or
`unknown` (`PGRST100`). It never raises on a malformed node.

# `where`

```elixir
@spec where(Ecto.Queryable.t(), [ast()], [option()]) ::
  {:ok, Ecto.Query.t()} | {:error, PgRest.Error.t()}
```

Adds one `where` per node to `queryable`. `:schema` defaults to the query's schema.

Returns the first node's error, if any.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
