# `PgRest.SQL.Call`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/sql/call.ex#L1)

Compiles the function call of an RPC (`PgRest.Plan.Call`) to the `FROM` item the root of its
read plan reads, following PostgREST's `callPlanToQuery`.

The item is one parenthesised subquery exposing the result columns: a resource return under
its Ecto field names (`PgRest.SQL.ScopedSource.projection/3`), any other composite under its
own column names, and a scalar or void return as `pgrst_scalar`. Inside it the call is aliased
`pgrst_call`:

  * `{:direct, args}` - `"s"."f"("a" := $n::text::<type>, VARIADIC "v" := $m::text[]::<type>)`:
    each value is one text parameter cast in SQL; a variadic one binds the list natively as
    `text[]`
  * `{:json, body, keys}` - the body bound once, `(SELECT $n::text::json AS json_data)
    pgrst_payload`, expanded with `json_to_recordset` (an object counts as an array of one)
    into `pgrst_body`, of which only the first element is used (`LIMIT 1`: PostgREST calls
    the function once), then `LATERAL "s"."f"("k" := pgrst_body."k", ...)`
  * `{:single, body}` - `"s"."f"($n::text::<json|jsonb|text|xml>)` (`bytea` binds the bytes)

A scalar call is wrapped as `(SELECT "s"."f"(...) pgrst_scalar) pgrst_call`.

With a `scope` (`{resource, scoped_query}`, see `PgRest.Plan.Call`) only the rows a stored,
in-scope row matches survive: the same key and the same value in every mapped column,
probed with `PgRest.SQL.ScopedSource.exists_probe/4`. Fabricated rows and stored rows whose
attributes the function changed are both dropped. A scoped call reads the function
`WITH ORDINALITY` and its source adds that number as `pgrst_ordinality`, which no select
item reads; without a requested order the read sorts by it (`row_order/2`), so the probe
cannot reorder the function's rows.

Function, parameter and column names come from the registry and are quoted with
`PgRest.SQL.Builder.ident/1`; parameter and column types are catalog (or declared) text.

# `row_order`

```elixir
@spec row_order(PgRest.Plan.Call.t(), String.t()) :: iodata()
```

The `ORDER BY` that keeps a scoped call's rows in the function's own output order, read
under `alias_name`; `[]` for an unscoped call, which keeps PostgREST's statement shape.

# `source`

```elixir
@spec source(
  PgRest.Plan.Call.t(),
  nil | {module(), Ecto.Query.t()},
  PgRest.SQL.Builder.t()
) ::
  {iodata(), PgRest.SQL.Builder.t()}
```

The `FROM` item of the call, `{sql, builder}`. `scope` is `nil` or `{resource, scoped_query}`.

---

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