# `PgRest.Planner.Tree`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/planner/tree.ex#L1)

The plan tree: embed resolution through the schema graph, authorization of every
resource it touches, and the build of `PgRest.Plan.Read` nodes with their embeds.

`resolve/5` produces raw nodes (`%{module, items, children, depth}`, a child being
`%{embed, rel, out, node}`) without touching the database, so `authorize/4` can run on
them before any catalog query. `authorize/4` computes the scoped query and policy once
per node path (its effective schema decides where the catalog is read),
`build/6` validates columns against the per-resource infos and builds the plan, and
`put_sources/2` attaches the queries.

## Differences from PostgREST

Output keys longer than 63 bytes or starting with ..., pgrst_ or _postgrest_
are rejected to avoid alias collisions; duplicate embed output keys are rejected.

Read errors may name the generated root alias pgrst_t0 instead of the table.
Aggregates under to-one spreads with after_load/2 return PGRST127 because
those columns are merged after SQL execution.

# `authorize`

```elixir
@spec authorize(map(), PgRest.Request.t(), map(), keyword()) ::
  {:ok, map()} | {:error, PgRest.Error.t()}
```

Authorizes each node path and operation and computes its effective source once.

# `build`

```elixir
@spec build(map(), PgRest.Request.t(), map(), map(), map(), [String.t()]) ::
  {:ok, PgRest.Plan.Read.t()} | {:error, PgRest.Error.t()}
```

Builds the `Plan.Read` for a raw node, children first.

# `check_aggregates`

```elixir
@spec check_aggregates(map(), boolean()) :: :ok | {:error, PgRest.Error.t()}
```

Checks the aggregates of the raw tree. With aggregates disabled (`allowed?` false) any
aggregate at any depth is `PGRST123`. Otherwise an aggregate a to-many spread would have to
compute (its own, or one hoisted from a to-one spread below it) is `PGRST127`, as in
PostgREST, and so is one in a to-one spread over an `after_load/2` subtree (a merge, which
cannot hoist it), where PgRest fails closed. The legacy bare `count` is a plain field here:
it is no aggregate to upstream.

# `check_paths`

```elixir
@spec check_paths(map(), map()) :: :ok | {:error, PgRest.Error.t()}
```

Every embedded parameter must name an embed in the select (`PGRST108`).

# `modules`

```elixir
@spec modules(map()) :: [module()]
```

Every resource module of the raw tree.

# `put_sources`

```elixir
@spec put_sources(PgRest.Plan.Read.t(), map()) :: PgRest.Plan.Read.t()
```

Attaches the scoped Ecto queries of `sources/3` to the plan and numbers its embeds.

# `resolve`

```elixir
@spec resolve(PgRest.SchemaGraph.t(), module(), list(), pos_integer(), [String.t()]) ::
  {:ok, map()} | {:error, PgRest.Error.t()}
```

Resolves every embed of the select tree through the graph.

---

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