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

The embed half of the read compiler: lateral joins, the select items they add, spreads
and `embed=is.null` filters. Called from `PgRest.SQL.Read`, which compiles the child
nodes.

  * to-one: `LEFT JOIN LATERAL (<child>)`, rendered with `row_to_json(...)::jsonb`
  * to-many: `json_agg(<agg>)::jsonb` inside the lateral, `COALESCE(<agg>.<agg>, '[]')`
    in the outer select list
  * `!inner`: `INNER JOIN LATERAL ... ON <agg>.<agg> IS NOT NULL` (to-one: `ON TRUE`)
  * a spread merges a to-one embed's columns into the parent; a to-many spread yields
    one array per column, ordered by the child's order terms (the child keeps its
    limit and offset, as upstream does)
  * `embed=is.null` compares the lateral with `IS [NOT] DISTINCT FROM NULL`

# `joins`

```elixir
@spec joins(PgRest.Plan.Read.t(), PgRest.SQL.Builder.t(), map()) ::
  {[iodata()], [{iodata(), boolean()}], PgRest.SQL.Builder.t()}
```

The `{joins, select_items, builder}` of the plan's embeds. Each select item is
`{sql, group?}`: `group?` is false for an aggregate the parent computes, so the parent's
`GROUP BY` (`PgRest.SQL.Aggregate.group_by/2`) reads the same list. In a count query only the
embeds that can change the parent row count are joined.

# `null_filter`

```elixir
@spec null_filter(PgRest.Plan.Read.t(), String.t(), boolean()) :: iodata()
```

SQL of an `embed=is.null` leaf of the node's filters.

# `order_in_aggregate?`

```elixir
@spec order_in_aggregate?(PgRest.Plan.Embed.t() | nil) :: boolean()
```

Whether the child's `ORDER BY` moves into its aggregate (a to-many spread).

# `order_selects`

```elixir
@spec order_selects(
  PgRest.Plan.Read.t(),
  PgRest.Plan.Embed.t() | nil,
  PgRest.SQL.Builder.t()
) ::
  {[iodata()], PgRest.SQL.Builder.t()}
```

Extra select items of a to-many spread child: its order columns under unique names, so
the aggregate can order by them. The child's order leaves its own query.

# `projected_items`

```elixir
@spec projected_items(PgRest.Plan.Embed.t()) :: [
  {String.t(), PgRest.AST.Aggregate.t() | nil}
]
```

Output names and hoisted aggregates selected by a lateral, excluding empty embeds.

# `spread_columns`

```elixir
@spec spread_columns(PgRest.Plan.Read.t()) :: [String.t()]
```

The column names a spread (or merge) embed's plan exposes to its parent.

# `spread_items`

```elixir
@spec spread_items(PgRest.Plan.Read.t()) :: [
  {String.t(), PgRest.AST.Aggregate.t() | nil}
]
```

The columns a spread (or merge) embed's plan exposes to its parent, each with the aggregate
the parent applies to it: a (non-legacy) aggregate of the plan or of a spread below it, which
a to-one spread leaves to its parent (`PgRest.SQL.Aggregate`), else `nil`.

---

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