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

Compiles a `PgRest.Plan.Read` tree to one SQL statement, mirroring PostgREST's
`QueryBuilder.readPlanToQuery`.

Every node reads `FROM (<scoped source>) AS <alias>`, the source being the resource's
effective Ecto query (scope applied) spliced through `PgRest.SQL.ScopedSource`, so scope
holds at every embed depth and on many-to-many junctions. Embeds are lateral joins,
compiled by `PgRest.SQL.Read.Embed`.

`LIMIT` and `OFFSET` are bind parameters (`$n::text::bigint`) at every node; with
`max_limit` set the node's limit is `LEAST(<request limit>, <max_limit>)`.
Select casts go through `PgRest.SQL.Builder.cast/2` and JSON-path keys are bound.

`statement/3` wraps the root in PostgREST's `pgrst_source` shape and builds the JSON
in Postgres as text. Permission-capped totals are exact for every count mode;
otherwise a table's planned/estimated totals are filled in by the executor.

# `opts`

```elixir
@type opts() :: [
  source: {iodata(), PgRest.SQL.Builder.t()},
  ctes: iodata(),
  extra: iodata(),
  inserted: iodata(),
  written: iodata(),
  matched: iodata()
]
```

# `statement`

```elixir
@spec statement(PgRest.Plan.Read.t(), map(), opts()) :: {String.t(), [term()]}
```

The full statement: `{sql, params}` returning `total`, `page_total` and `body` (text in the
media type of `plan.output.media`: JSON, or CSV; a single-object type unwraps one row),
then `response_headers` and `response_status` (`PgRest.ResponseGucs`, read after the main
CTE in the same statement). A write's statement has its own columns between them.

## Options

  * `:source` - `{mutation_sql, builder}`: the `pgrst_source` CTE is that statement
    (a write's `RETURNING`, exposing columns under their Ecto field names) and the root
    reads `FROM pgrst_source`
  * `:ctes` - with `:source`, CTEs written before `pgrst_source`, each ending in `, `
  * `:extra` - with `:source`, one more select expression, returned as `pgrst_keys`
  * `:inserted` - with `:source`, one more select expression, returned as `pgrst_inserted`
  * `:written` - with `:source`, the number of rows the mutation wrote (before any
    embed filtering of the representation), returned as `pgrst_written`
  * `:matched` - with `:source`, the number of payload elements a `PUT` matched, returned as
    `pgrst_matched`

---

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